target stringlengths 5 300 | feat_repo_name stringlengths 6 76 | text stringlengths 26 1.05M |
|---|---|---|
fixtures/react.js | noamokman/eslint-config-noamokman | import React from 'react'; // eslint-disable-line import/no-extraneous-dependencies
export default () => <span aria-label='lol'>{'lol'}</span>; |
src/svg-icons/action/translate.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionTranslate = (props) => (
<SvgIcon {...props}>
<path d="M12.87 15.07l-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</SvgIcon>
);
ActionTranslate = pure(ActionTranslate);
ActionTranslate.displayName = 'ActionTranslate';
export default ActionTranslate;
|
src/icons/HelpOutlineIcon.js | kiloe/ui | import React from 'react';
import Icon from '../Icon';
export default class HelpOutlineIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z"/></svg>;}
}; |
ajax/libs/react-virtualized/7.11.3/react-virtualized.js | Piicksarn/cdnjs | !function(root, factory) {
"object" == typeof exports && "object" == typeof module ? module.exports = factory(require("React"), require("React.addons.shallowCompare"), require("ReactDOM")) : "function" == typeof define && define.amd ? define([ "React", "React.addons.shallowCompare", "ReactDOM" ], factory) : "object" == typeof exports ? exports.ReactVirtualized = factory(require("React"), require("React.addons.shallowCompare"), require("ReactDOM")) : root.ReactVirtualized = factory(root.React, root["React.addons.shallowCompare"], root.ReactDOM);
}(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_10__) {
/******/
return function(modules) {
/******/
/******/
// The require function
/******/
function __webpack_require__(moduleId) {
/******/
/******/
// Check if module is in cache
/******/
if (installedModules[moduleId]) /******/
return installedModules[moduleId].exports;
/******/
/******/
// Create a new module (and put it into the cache)
/******/
var module = installedModules[moduleId] = {
/******/
exports: {},
/******/
id: moduleId,
/******/
loaded: !1
};
/******/
/******/
// Return the exports of the module
/******/
/******/
/******/
// Execute the module function
/******/
/******/
/******/
// Flag the module as loaded
/******/
return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__),
module.loaded = !0, module.exports;
}
// webpackBootstrap
/******/
// The module cache
/******/
var installedModules = {};
/******/
/******/
// Load entry module and return exports
/******/
/******/
/******/
/******/
// expose the modules object (__webpack_modules__)
/******/
/******/
/******/
// expose the module cache
/******/
/******/
/******/
// __webpack_public_path__
/******/
return __webpack_require__.m = modules, __webpack_require__.c = installedModules,
__webpack_require__.p = "", __webpack_require__(0);
}([ /* 0 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _ArrowKeyStepper = __webpack_require__(1);
Object.defineProperty(exports, "ArrowKeyStepper", {
enumerable: !0,
get: function() {
return _ArrowKeyStepper.ArrowKeyStepper;
}
});
var _AutoSizer = __webpack_require__(5);
Object.defineProperty(exports, "AutoSizer", {
enumerable: !0,
get: function() {
return _AutoSizer.AutoSizer;
}
});
var _CellMeasurer = __webpack_require__(8);
Object.defineProperty(exports, "CellMeasurer", {
enumerable: !0,
get: function() {
return _CellMeasurer.CellMeasurer;
}
});
var _Collection = __webpack_require__(169);
Object.defineProperty(exports, "Collection", {
enumerable: !0,
get: function() {
return _Collection.Collection;
}
});
var _ColumnSizer = __webpack_require__(182);
Object.defineProperty(exports, "ColumnSizer", {
enumerable: !0,
get: function() {
return _ColumnSizer.ColumnSizer;
}
});
var _FlexTable = __webpack_require__(192);
Object.defineProperty(exports, "FlexTable", {
enumerable: !0,
get: function() {
return _FlexTable.FlexTable;
}
}), Object.defineProperty(exports, "FlexColumn", {
enumerable: !0,
get: function() {
return _FlexTable.FlexColumn;
}
}), Object.defineProperty(exports, "SortDirection", {
enumerable: !0,
get: function() {
return _FlexTable.SortDirection;
}
}), Object.defineProperty(exports, "SortIndicator", {
enumerable: !0,
get: function() {
return _FlexTable.SortIndicator;
}
});
var _Grid = __webpack_require__(184);
Object.defineProperty(exports, "defaultCellRangeRenderer", {
enumerable: !0,
get: function() {
return _Grid.defaultCellRangeRenderer;
}
}), Object.defineProperty(exports, "Grid", {
enumerable: !0,
get: function() {
return _Grid.Grid;
}
});
var _InfiniteLoader = __webpack_require__(200);
Object.defineProperty(exports, "InfiniteLoader", {
enumerable: !0,
get: function() {
return _InfiniteLoader.InfiniteLoader;
}
});
var _ScrollSync = __webpack_require__(202);
Object.defineProperty(exports, "ScrollSync", {
enumerable: !0,
get: function() {
return _ScrollSync.ScrollSync;
}
});
var _VirtualScroll = __webpack_require__(204);
Object.defineProperty(exports, "VirtualScroll", {
enumerable: !0,
get: function() {
return _VirtualScroll.VirtualScroll;
}
});
var _WindowScroller = __webpack_require__(206);
Object.defineProperty(exports, "WindowScroller", {
enumerable: !0,
get: function() {
return _WindowScroller.WindowScroller;
}
});
}, /* 1 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.ArrowKeyStepper = exports["default"] = void 0;
var _ArrowKeyStepper2 = __webpack_require__(2), _ArrowKeyStepper3 = _interopRequireDefault(_ArrowKeyStepper2);
exports["default"] = _ArrowKeyStepper3["default"], exports.ArrowKeyStepper = _ArrowKeyStepper3["default"];
}, /* 2 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ArrowKeyStepper = function(_Component) {
function ArrowKeyStepper(props, context) {
_classCallCheck(this, ArrowKeyStepper);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ArrowKeyStepper).call(this, props, context));
return _this.state = {
scrollToColumn: 0,
scrollToRow: 0
}, _this._columnStartIndex = 0, _this._columnStopIndex = 0, _this._rowStartIndex = 0,
_this._rowStopIndex = 0, _this._onKeyDown = _this._onKeyDown.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this),
_this;
}
return _inherits(ArrowKeyStepper, _Component), _createClass(ArrowKeyStepper, [ {
key: "render",
value: function() {
var _props = this.props, className = _props.className, children = _props.children, _state = this.state, scrollToColumn = _state.scrollToColumn, scrollToRow = _state.scrollToRow;
return _react2["default"].createElement("div", {
className: className,
onKeyDown: this._onKeyDown
}, children({
onSectionRendered: this._onSectionRendered,
scrollToColumn: scrollToColumn,
scrollToRow: scrollToRow
}));
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_onKeyDown",
value: function(event) {
var _props2 = this.props, columnCount = _props2.columnCount, rowCount = _props2.rowCount;
switch (event.key) {
case "ArrowDown":
event.preventDefault(), this.setState({
scrollToRow: Math.min(this._rowStopIndex + 1, rowCount - 1)
});
break;
case "ArrowLeft":
event.preventDefault(), this.setState({
scrollToColumn: Math.max(this._columnStartIndex - 1, 0)
});
break;
case "ArrowRight":
event.preventDefault(), this.setState({
scrollToColumn: Math.min(this._columnStopIndex + 1, columnCount - 1)
});
break;
case "ArrowUp":
event.preventDefault(), this.setState({
scrollToRow: Math.max(this._rowStartIndex - 1, 0)
});
}
}
}, {
key: "_onSectionRendered",
value: function(_ref) {
var columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex;
this._columnStartIndex = columnStartIndex, this._columnStopIndex = columnStopIndex,
this._rowStartIndex = rowStartIndex, this._rowStopIndex = rowStopIndex;
}
} ]), ArrowKeyStepper;
}(_react.Component);
ArrowKeyStepper.propTypes = {
children: _react.PropTypes.func.isRequired,
className: _react.PropTypes.string,
columnCount: _react.PropTypes.number.isRequired,
rowCount: _react.PropTypes.number.isRequired
}, exports["default"] = ArrowKeyStepper;
}, /* 3 */
/***/
function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
}, /* 4 */
/***/
function(module, exports) {
module.exports = React.addons.shallowCompare;
}, /* 5 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.AutoSizer = exports["default"] = void 0;
var _AutoSizer2 = __webpack_require__(6), _AutoSizer3 = _interopRequireDefault(_AutoSizer2);
exports["default"] = _AutoSizer3["default"], exports.AutoSizer = _AutoSizer3["default"];
}, /* 6 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), AutoSizer = function(_Component) {
function AutoSizer(props) {
_classCallCheck(this, AutoSizer);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AutoSizer).call(this, props));
return _this.state = {
height: 0,
width: 0
}, _this._onResize = _this._onResize.bind(_this), _this._onScroll = _this._onScroll.bind(_this),
_this._setRef = _this._setRef.bind(_this), _this;
}
return _inherits(AutoSizer, _Component), _createClass(AutoSizer, [ {
key: "componentDidMount",
value: function() {
this._detectElementResize = __webpack_require__(7), this._detectElementResize.addResizeListener(this._parentNode, this._onResize),
this._onResize();
}
}, {
key: "componentWillUnmount",
value: function() {
this._detectElementResize && this._detectElementResize.removeResizeListener(this._parentNode, this._onResize);
}
}, {
key: "render",
value: function() {
var _props = this.props, children = _props.children, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = this.state, height = _state.height, width = _state.width, outerStyle = {
overflow: "visible"
};
return disableHeight || (outerStyle.height = 0), disableWidth || (outerStyle.width = 0),
_react2["default"].createElement("div", {
ref: this._setRef,
onScroll: this._onScroll,
style: outerStyle
}, children({
height: height,
width: width
}));
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_onResize",
value: function() {
var onResize = this.props.onResize, boundingRect = this._parentNode.getBoundingClientRect(), height = boundingRect.height || 0, width = boundingRect.width || 0, style = getComputedStyle(this._parentNode), paddingLeft = parseInt(style.paddingLeft, 10) || 0, paddingRight = parseInt(style.paddingRight, 10) || 0, paddingTop = parseInt(style.paddingTop, 10) || 0, paddingBottom = parseInt(style.paddingBottom, 10) || 0;
this.setState({
height: height - paddingTop - paddingBottom,
width: width - paddingLeft - paddingRight
}), onResize({
height: height,
width: width
});
}
}, {
key: "_onScroll",
value: function(event) {
event.stopPropagation();
}
}, {
key: "_setRef",
value: function(autoSizer) {
this._parentNode = autoSizer && autoSizer.parentNode;
}
} ]), AutoSizer;
}(_react.Component);
AutoSizer.propTypes = {
children: _react.PropTypes.func.isRequired,
disableHeight: _react.PropTypes.bool,
disableWidth: _react.PropTypes.bool,
onResize: _react.PropTypes.func.isRequired
}, AutoSizer.defaultProps = {
onResize: function() {}
}, exports["default"] = AutoSizer;
}, /* 7 */
/***/
function(module, exports) {
"use strict";
var _window;
_window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : void 0;
var attachEvent = "undefined" != typeof document && document.attachEvent, stylesCreated = !1;
if (!attachEvent) {
var requestFrame = function() {
var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) {
return _window.setTimeout(fn, 20);
};
return function(fn) {
return raf(fn);
};
}(), cancelFrame = function() {
var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout;
return function(id) {
return cancel(id);
};
}(), resetTriggers = function(element) {
var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild;
contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight,
expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px",
expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight;
}, checkTriggers = function(element) {
return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height;
}, scrollListener = function(e) {
var element = this;
resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() {
checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight,
element.__resizeListeners__.forEach(function(fn) {
fn.call(element, e);
}));
});
}, animation = !1, animationstring = "animation", keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElement("fakeelement");
if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) {
pfx = domPrefixes[i], animationstring = pfx + "Animation", keyframeprefix = "-" + pfx.toLowerCase() + "-",
animationstartevent = startEvents[i], animation = !0;
break;
}
var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; ";
}
var createStyles = function() {
if (!stylesCreated) {
var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + 'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName("head")[0], style = document.createElement("style");
style.type = "text/css", style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)),
head.appendChild(style), stylesCreated = !0;
}
}, addResizeListener = function(element, fn) {
attachEvent ? element.attachEvent("onresize", fn) : (element.__resizeTriggers__ || ("static" == getComputedStyle(element).position && (element.style.position = "relative"),
createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElement("div")).className = "resize-triggers",
element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>',
element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0),
animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function(e) {
e.animationName == animationName && resetTriggers(element);
})), element.__resizeListeners__.push(fn));
}, removeResizeListener = function(element, fn) {
attachEvent ? element.detachEvent("onresize", fn) : (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1),
element.__resizeListeners__.length || (element.removeEventListener("scroll", scrollListener, !0),
element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__)));
};
module.exports = {
addResizeListener: addResizeListener,
removeResizeListener: removeResizeListener
};
}, /* 8 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.CellMeasurer = exports["default"] = void 0;
var _CellMeasurer2 = __webpack_require__(9), _CellMeasurer3 = _interopRequireDefault(_CellMeasurer2);
exports["default"] = _CellMeasurer3["default"], exports.CellMeasurer = _CellMeasurer3["default"];
}, /* 9 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactDom2 = _interopRequireDefault(_reactDom), _server = __webpack_require__(11), _server2 = _interopRequireDefault(_server), CellMeasurer = function(_Component) {
function CellMeasurer(props, state) {
_classCallCheck(this, CellMeasurer);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CellMeasurer).call(this, props, state));
return _this._cachedColumnWidths = {}, _this._cachedRowHeights = {}, _this.getColumnWidth = _this.getColumnWidth.bind(_this),
_this.getRowHeight = _this.getRowHeight.bind(_this), _this.resetMeasurements = _this.resetMeasurements.bind(_this),
_this;
}
return _inherits(CellMeasurer, _Component), _createClass(CellMeasurer, [ {
key: "getColumnWidth",
value: function(_ref) {
var index = _ref.index;
if (this._cachedColumnWidths[index]) return this._cachedColumnWidths[index];
for (var rowCount = this.props.rowCount, maxWidth = 0, rowIndex = 0; rowCount > rowIndex; rowIndex++) {
var _measureCell2 = this._measureCell({
clientWidth: !0,
columnIndex: index,
rowIndex: rowIndex
}), width = _measureCell2.width;
maxWidth = Math.max(maxWidth, width);
}
return this._cachedColumnWidths[index] = maxWidth, maxWidth;
}
}, {
key: "getRowHeight",
value: function(_ref2) {
var index = _ref2.index;
if (this._cachedRowHeights[index]) return this._cachedRowHeights[index];
for (var columnCount = this.props.columnCount, maxHeight = 0, columnIndex = 0; columnCount > columnIndex; columnIndex++) {
var _measureCell3 = this._measureCell({
clientHeight: !0,
columnIndex: columnIndex,
rowIndex: index
}), height = _measureCell3.height;
maxHeight = Math.max(maxHeight, height);
}
return this._cachedRowHeights[index] = maxHeight, maxHeight;
}
}, {
key: "resetMeasurements",
value: function() {
this._cachedColumnWidths = {}, this._cachedRowHeights = {};
}
}, {
key: "componentDidMount",
value: function() {
this._renderAndMount();
}
}, {
key: "componentWillReceiveProps",
value: function(nextProps) {
this._updateDivDimensions(nextProps);
}
}, {
key: "componentWillUnmount",
value: function() {
this._unmountContainer();
}
}, {
key: "render",
value: function() {
var children = this.props.children;
return children({
getColumnWidth: this.getColumnWidth,
getRowHeight: this.getRowHeight,
resetMeasurements: this.resetMeasurements
});
}
}, {
key: "_getContainerNode",
value: function(props) {
var container = props.container;
return container ? _reactDom2["default"].findDOMNode("function" == typeof container ? container() : container) : document.body;
}
}, {
key: "_measureCell",
value: function(_ref3) {
var _ref3$clientHeight = _ref3.clientHeight, clientHeight = void 0 === _ref3$clientHeight ? !1 : _ref3$clientHeight, _ref3$clientWidth = _ref3.clientWidth, clientWidth = void 0 === _ref3$clientWidth ? !0 : _ref3$clientWidth, columnIndex = _ref3.columnIndex, rowIndex = _ref3.rowIndex, cellRenderer = this.props.cellRenderer, rendered = cellRenderer({
columnIndex: columnIndex,
rowIndex: rowIndex
});
return this._renderAndMount(), this._div.innerHTML = _server2["default"].renderToString(rendered),
{
height: clientHeight && this._div.clientHeight,
width: clientWidth && this._div.clientWidth
};
}
}, {
key: "_renderAndMount",
value: function() {
this._div || (this._div = document.createElement("div"), this._div.style.display = "inline-block",
this._div.style.position = "absolute", this._div.style.visibility = "hidden", this._div.style.zIndex = -1,
this._updateDivDimensions(this.props), this._containerNode = this._getContainerNode(this.props),
this._containerNode.appendChild(this._div));
}
}, {
key: "_unmountContainer",
value: function() {
this._div && (this._containerNode.removeChild(this._div), this._div = null), this._containerNode = null;
}
}, {
key: "_updateDivDimensions",
value: function(props) {
var height = props.height, width = props.width;
height && height !== this._divHeight && (this._divHeight = height, this._div.style.height = height + "px"),
width && width !== this._divWidth && (this._divWidth = width, this._div.style.width = width + "px");
}
} ]), CellMeasurer;
}(_react.Component);
CellMeasurer.propTypes = {
cellRenderer: _react.PropTypes.func.isRequired,
children: _react.PropTypes.func.isRequired,
columnCount: _react.PropTypes.number.isRequired,
container: _react2["default"].PropTypes.oneOfType([ _react2["default"].PropTypes.func, _react2["default"].PropTypes.node ]),
height: _react.PropTypes.number,
rowCount: _react.PropTypes.number.isRequired,
width: _react.PropTypes.number
}, exports["default"] = CellMeasurer;
}, /* 10 */
/***/
function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_10__;
}, /* 11 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(12);
}, /* 12 */
/***/
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 ReactDOMServer
*/
"use strict";
var ReactDefaultInjection = __webpack_require__(13), ReactServerRendering = __webpack_require__(163), ReactVersion = __webpack_require__(168);
ReactDefaultInjection.inject();
var ReactDOMServer = {
renderToString: ReactServerRendering.renderToString,
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
version: ReactVersion
};
module.exports = ReactDOMServer;
}, /* 13 */
/***/
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 ReactDefaultInjection
*/
"use strict";
function inject() {
alreadyInjected || (alreadyInjected = !0, ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener),
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder), ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree),
ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal), ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
}), ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent),
ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent),
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig), ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig),
ReactInjection.EmptyComponent.injectEmptyComponentFactory(function(instantiate) {
return new ReactDOMEmptyComponent(instantiate);
}), ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction),
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy), ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment));
}
var BeforeInputEventPlugin = __webpack_require__(14), ChangeEventPlugin = __webpack_require__(37), DefaultEventPluginOrder = __webpack_require__(58), EnterLeaveEventPlugin = __webpack_require__(59), HTMLDOMPropertyConfig = __webpack_require__(64), ReactComponentBrowserEnvironment = __webpack_require__(65), ReactDOMComponent = __webpack_require__(79), ReactDOMComponentTree = __webpack_require__(38), ReactDOMEmptyComponent = __webpack_require__(131), ReactDOMTreeTraversal = __webpack_require__(132), ReactDOMTextComponent = __webpack_require__(133), ReactDefaultBatchingStrategy = __webpack_require__(134), ReactEventListener = __webpack_require__(135), ReactInjection = __webpack_require__(138), ReactReconcileTransaction = __webpack_require__(142), SVGDOMPropertyConfig = __webpack_require__(150), SelectEventPlugin = __webpack_require__(151), SimpleEventPlugin = __webpack_require__(152), alreadyInjected = !1;
module.exports = {
inject: inject
};
}, /* 14 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BeforeInputEventPlugin
*/
"use strict";
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return "object" == typeof opera && "function" == typeof opera.version && parseInt(opera.version(), 10) <= 12;
}
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && !(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return !0;
default:
return !1;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
return "object" == typeof detail && "data" in detail ? detail.data : null;
}
/**
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var eventType, fallbackData;
if (canUseCompositionEvent ? eventType = getCompositionEventType(topLevelType) : currentComposition ? isFallbackCompositionEnd(topLevelType, nativeEvent) && (eventType = eventTypes.compositionEnd) : isFallbackCompositionStart(topLevelType, nativeEvent) && (eventType = eventTypes.compositionStart),
!eventType) return null;
useFallbackCompositionData && (// The current composition is stored statically and must not be
// overwritten while composition continues.
currentComposition || eventType !== eventTypes.compositionStart ? eventType === eventTypes.compositionEnd && currentComposition && (fallbackData = currentComposition.getData()) : currentComposition = FallbackCompositionState.getPooled(nativeEventTarget));
var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
if (fallbackData) // Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData; else {
var customData = getDataFromCustomEvent(nativeEvent);
null !== customData && (event.data = customData);
}
return EventPropagators.accumulateTwoPhaseDispatches(event), event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topCompositionEnd:
return getDataFromCustomEvent(nativeEvent);
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
return which !== SPACEBAR_CODE ? null : (hasSpaceKeypress = !0, SPACEBAR_CHAR);
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
return chars === SPACEBAR_CHAR && hasSpaceKeypress ? null : chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
if (currentComposition) {
if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) {
var chars = currentComposition.getData();
return FallbackCompositionState.release(currentComposition), currentComposition = null,
chars;
}
return null;
}
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
return nativeEvent.which && !isKeypressCommand(nativeEvent) ? String.fromCharCode(nativeEvent.which) : null;
case topLevelTypes.topCompositionEnd:
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var chars;
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (chars = canUseTextInputEvent ? getNativeBeforeInputChars(topLevelType, nativeEvent) : getFallbackBeforeInputChars(topLevelType, nativeEvent),
!chars) return null;
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
return event.data = chars, EventPropagators.accumulateTwoPhaseDispatches(event),
event;
}
var EventConstants = __webpack_require__(15), EventPropagators = __webpack_require__(19), ExecutionEnvironment = __webpack_require__(28), FallbackCompositionState = __webpack_require__(29), SyntheticCompositionEvent = __webpack_require__(33), SyntheticInputEvent = __webpack_require__(35), keyOf = __webpack_require__(36), END_KEYCODES = [ 9, 13, 27, 32 ], START_KEYCODE = 229, canUseCompositionEvent = ExecutionEnvironment.canUseDOM && "CompositionEvent" in window, documentMode = null;
ExecutionEnvironment.canUseDOM && "documentMode" in document && (documentMode = document.documentMode);
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && "TextEvent" in window && !documentMode && !isPresto(), useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && 11 >= documentMode), SPACEBAR_CODE = 32, SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE), topLevelTypes = EventConstants.topLevelTypes, eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({
onBeforeInput: null
}),
captured: keyOf({
onBeforeInputCapture: null
})
},
dependencies: [ topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste ]
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({
onCompositionEnd: null
}),
captured: keyOf({
onCompositionEndCapture: null
})
},
dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({
onCompositionStart: null
}),
captured: keyOf({
onCompositionStartCapture: null
})
},
dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({
onCompositionUpdate: null
}),
captured: keyOf({
onCompositionUpdateCapture: null
})
},
dependencies: [ topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown ]
}
}, hasSpaceKeypress = !1, currentComposition = null, BeforeInputEventPlugin = {
eventTypes: eventTypes,
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
return [ extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) ];
}
};
module.exports = BeforeInputEventPlugin;
}, /* 15 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventConstants
*/
"use strict";
var keyMirror = __webpack_require__(16), PropagationPhases = keyMirror({
bubbled: null,
captured: null
}), topLevelTypes = keyMirror({
topAbort: null,
topAnimationEnd: null,
topAnimationIteration: null,
topAnimationStart: null,
topBlur: null,
topCanPlay: null,
topCanPlayThrough: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topDurationChange: null,
topEmptied: null,
topEncrypted: null,
topEnded: null,
topError: null,
topFocus: null,
topInput: null,
topInvalid: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topLoadedData: null,
topLoadedMetadata: null,
topLoadStart: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topPause: null,
topPlay: null,
topPlaying: null,
topProgress: null,
topRateChange: null,
topReset: null,
topScroll: null,
topSeeked: null,
topSeeking: null,
topSelectionChange: null,
topStalled: null,
topSubmit: null,
topSuspend: null,
topTextInput: null,
topTimeUpdate: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topTransitionEnd: null,
topVolumeChange: null,
topWaiting: null,
topWheel: null
}), EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
}, /* 16 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks static-only
*/
"use strict";
var invariant = __webpack_require__(18), keyMirror = function(obj) {
var key, ret = {};
obj instanceof Object && !Array.isArray(obj) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "keyMirror(...): Argument must be an object.") : invariant(!1);
for (key in obj) obj.hasOwnProperty(key) && (ret[key] = key);
return ret;
};
module.exports = keyMirror;
}).call(exports, __webpack_require__(17));
}, /* 17 */
/***/
function(module, exports) {
function cleanUpNextTick() {
draining && currentQueue && (draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1,
queue.length && drainQueue());
}
function drainQueue() {
if (!draining) {
var timeout = setTimeout(cleanUpNextTick);
draining = !0;
for (var len = queue.length; len; ) {
for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run();
queueIndex = -1, len = queue.length;
}
currentQueue = null, draining = !1, clearTimeout(timeout);
}
}
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun, this.array = array;
}
function noop() {}
// shim for using process in browser
var currentQueue, process = module.exports = {}, queue = [], draining = !1, queueIndex = -1;
process.nextTick = function(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i];
queue.push(new Item(fun, args)), 1 !== queue.length || draining || setTimeout(drainQueue, 0);
}, Item.prototype.run = function() {
this.fun.apply(null, this.array);
}, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [],
process.version = "", // empty string to avoid regexp issues
process.versions = {}, process.on = noop, process.addListener = noop, process.once = noop,
process.off = noop, process.removeListener = noop, process.removeAllListeners = noop,
process.emit = noop, process.binding = function(name) {
throw new Error("process.binding is not supported");
}, process.cwd = function() {
return "/";
}, process.chdir = function(dir) {
throw new Error("process.chdir is not supported");
}, process.umask = function() {
return 0;
};
}, /* 18 */
/***/
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 ("production" !== process.env.NODE_ENV && void 0 === format) throw new Error("invariant requires an error message argument");
if (!condition) {
var error;
if (void 0 === format) 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 ], argIndex = 0;
error = new Error(format.replace(/%s/g, function() {
return args[argIndex++];
})), error.name = "Invariant Violation";
}
// we don't care about invariant's own frame
throw error.framesToPop = 1, error;
}
}
module.exports = invariant;
}).call(exports, __webpack_require__(17));
}, /* 19 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPropagators
*/
"use strict";
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(inst, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(inst, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(inst, upwards, event) {
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(inst, "Dispatching inst must not be null") : void 0);
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured, listener = listenerAtPhase(inst, event, phase);
listener && (event._dispatchListeners = accumulateInto(event._dispatchListeners, listener),
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst));
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We cannot perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
event && event.dispatchConfig.phasedRegistrationNames && EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
var targetInst = event._targetInst, parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null;
EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(inst, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName, listener = getListener(inst, registrationName);
listener && (event._dispatchListeners = accumulateInto(event._dispatchListeners, listener),
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst));
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
event && event.dispatchConfig.registrationName && accumulateDispatches(event._targetInst, null, event);
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, from, to) {
EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
var EventConstants = __webpack_require__(15), EventPluginHub = __webpack_require__(20), EventPluginUtils = __webpack_require__(22), accumulateInto = __webpack_require__(26), forEachAccumulated = __webpack_require__(27), warning = __webpack_require__(24), PropagationPhases = EventConstants.PropagationPhases, getListener = EventPluginHub.getListener, EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
}).call(exports, __webpack_require__(17));
}, /* 20 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginHub
*/
"use strict";
var EventPluginRegistry = __webpack_require__(21), EventPluginUtils = __webpack_require__(22), ReactErrorUtils = __webpack_require__(23), accumulateInto = __webpack_require__(26), forEachAccumulated = __webpack_require__(27), invariant = __webpack_require__(18), listenerBank = {}, eventQueue = null, executeDispatchesAndRelease = function(event, simulated) {
event && (EventPluginUtils.executeDispatchesInOrder(event, simulated), event.isPersistent() || event.constructor.release(event));
}, executeDispatchesAndReleaseSimulated = function(e) {
return executeDispatchesAndRelease(e, !0);
}, executeDispatchesAndReleaseTopLevel = function(e) {
return executeDispatchesAndRelease(e, !1);
}, EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {function} listener The callback to store.
*/
putListener: function(inst, registrationName, listener) {
"function" != typeof listener ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected %s listener to be a function, instead got type %s", registrationName, typeof listener) : invariant(!1) : void 0;
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[inst._rootNodeID] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
PluginModule && PluginModule.didPutListener && PluginModule.didPutListener(inst, registrationName, listener);
},
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function(inst, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[inst._rootNodeID];
},
/**
* Deletes a listener from the registration bank.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function(inst, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
PluginModule && PluginModule.willDeleteListener && PluginModule.willDeleteListener(inst, registrationName);
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
bankForRegistrationName && delete bankForRegistrationName[inst._rootNodeID];
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {object} inst The instance, which is the source of events.
*/
deleteAllListeners: function(inst) {
for (var registrationName in listenerBank) if (listenerBank[registrationName][inst._rootNodeID]) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
PluginModule && PluginModule.willDeleteListener && PluginModule.willDeleteListener(inst, registrationName),
delete listenerBank[registrationName][inst._rootNodeID];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
for (var events, plugins = EventPluginRegistry.plugins, i = 0; i < plugins.length; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
extractedEvents && (events = accumulateInto(events, extractedEvents));
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function(events) {
events && (eventQueue = accumulateInto(eventQueue, events));
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function(simulated) {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null, simulated ? forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated) : forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel),
eventQueue ? "production" !== process.env.NODE_ENV ? invariant(!1, "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.") : invariant(!1) : void 0,
ReactErrorUtils.rethrowCaughtError();
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function() {
listenerBank = {};
},
__getListenerBank: function() {
return listenerBank;
}
};
module.exports = EventPluginHub;
}).call(exports, __webpack_require__(17));
}, /* 21 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginRegistry
*/
"use strict";
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (EventPluginOrder) for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName], pluginIndex = EventPluginOrder.indexOf(pluginName);
if (pluginIndex > -1 ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.", pluginName) : invariant(!1),
!EventPluginRegistry.plugins[pluginIndex]) {
PluginModule.extractEvents ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.", pluginName) : invariant(!1),
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.", eventName, pluginName) : invariant(!1);
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.", eventName) : invariant(!1) : void 0,
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, PluginModule, eventName);
}
return !0;
}
return dispatchConfig.registrationName ? (publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName),
!0) : !1;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule, eventName) {
if (EventPluginRegistry.registrationNameModules[registrationName] ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.", registrationName) : invariant(!1) : void 0,
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule, EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies,
"production" !== process.env.NODE_ENV) {
var lowerCasedName = registrationName.toLowerCase();
EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName;
}
}
var invariant = __webpack_require__(18), EventPluginOrder = null, namesToPlugins = {}, EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in __DEV__.
* @type {Object}
*/
possibleRegistrationNames: "production" !== process.env.NODE_ENV ? {} : null,
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function(InjectedEventPluginOrder) {
EventPluginOrder ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.") : invariant(!1) : void 0,
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder), recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function(injectedNamesToPlugins) {
var isOrderingDirty = !1;
for (var pluginName in injectedNamesToPlugins) if (injectedNamesToPlugins.hasOwnProperty(pluginName)) {
var PluginModule = injectedNamesToPlugins[pluginName];
namesToPlugins.hasOwnProperty(pluginName) && namesToPlugins[pluginName] === PluginModule || (namesToPlugins[pluginName] ? "production" !== process.env.NODE_ENV ? invariant(!1, "EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.", pluginName) : invariant(!1) : void 0,
namesToPlugins[pluginName] = PluginModule, isOrderingDirty = !0);
}
isOrderingDirty && recomputePluginOrdering();
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function(event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
for (var phase in dispatchConfig.phasedRegistrationNames) if (dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];
if (PluginModule) return PluginModule;
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function() {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) namesToPlugins.hasOwnProperty(pluginName) && delete namesToPlugins[pluginName];
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) eventNameDispatchConfigs.hasOwnProperty(eventName) && delete eventNameDispatchConfigs[eventName];
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) registrationNameModules.hasOwnProperty(registrationName) && delete registrationNameModules[registrationName];
if ("production" !== process.env.NODE_ENV) {
var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames;
for (var lowerCasedName in possibleRegistrationNames) possibleRegistrationNames.hasOwnProperty(lowerCasedName) && delete possibleRegistrationNames[lowerCasedName];
}
}
};
module.exports = EventPluginRegistry;
}).call(exports, __webpack_require__(17));
}, /* 22 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginUtils
*/
"use strict";
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart;
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @param {function} listener Application-level callback
* @param {*} inst Internal component instance
*/
function executeDispatch(event, simulated, listener, inst) {
var type = event.type || "unknown-event";
event.currentTarget = EventPluginUtils.getNodeFromInstance(inst), simulated ? ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event) : ReactErrorUtils.invokeGuardedCallback(type, listener, event),
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances;
if ("production" !== process.env.NODE_ENV && validateEventDispatches(event), Array.isArray(dispatchListeners)) for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) // Listeners and Instances are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); else dispatchListeners && executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
event._dispatchListeners = null, event._dispatchInstances = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances;
if ("production" !== process.env.NODE_ENV && validateEventDispatches(event), Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length && !event.isPropagationStopped(); i++) // Listeners and Instances are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchInstances[i])) return dispatchInstances[i];
} else if (dispatchListeners && dispatchListeners(event, dispatchInstances)) return dispatchInstances;
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
return event._dispatchInstances = null, event._dispatchListeners = null, ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
"production" !== process.env.NODE_ENV && validateEventDispatches(event);
var dispatchListener = event._dispatchListeners, dispatchInstance = event._dispatchInstances;
Array.isArray(dispatchListener) ? "production" !== process.env.NODE_ENV ? invariant(!1, "executeDirectDispatch(...): Invalid `event`.") : invariant(!1) : void 0,
event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null;
var res = dispatchListener ? dispatchListener(event) : null;
return event.currentTarget = null, event._dispatchListeners = null, event._dispatchInstances = null,
res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
var ComponentTree, TreeTraversal, validateEventDispatches, EventConstants = __webpack_require__(15), ReactErrorUtils = __webpack_require__(23), invariant = __webpack_require__(18), warning = __webpack_require__(24), injection = {
injectComponentTree: function(Injected) {
ComponentTree = Injected, "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, "EventPluginUtils.injection.injectComponentTree(...): Injected module is missing getNodeFromInstance or getInstanceFromNode.") : void 0);
},
injectTreeTraversal: function(Injected) {
TreeTraversal = Injected, "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, "EventPluginUtils.injection.injectTreeTraversal(...): Injected module is missing isAncestor or getLowestCommonAncestor.") : void 0);
}
}, topLevelTypes = EventConstants.topLevelTypes;
"production" !== process.env.NODE_ENV && (validateEventDispatches = function(event) {
var dispatchListeners = event._dispatchListeners, dispatchInstances = event._dispatchInstances, listenersIsArr = Array.isArray(dispatchListeners), listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0, instancesIsArr = Array.isArray(dispatchInstances), instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
"production" !== process.env.NODE_ENV ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, "EventPluginUtils: Invalid `event`.") : void 0;
});
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getInstanceFromNode: function(node) {
return ComponentTree.getInstanceFromNode(node);
},
getNodeFromInstance: function(node) {
return ComponentTree.getNodeFromInstance(node);
},
isAncestor: function(a, b) {
return TreeTraversal.isAncestor(a, b);
},
getLowestCommonAncestor: function(a, b) {
return TreeTraversal.getLowestCommonAncestor(a, b);
},
getParentInstance: function(inst) {
return TreeTraversal.getParentInstance(inst);
},
traverseTwoPhase: function(target, fn, arg) {
return TreeTraversal.traverseTwoPhase(target, fn, arg);
},
traverseEnterLeave: function(from, to, fn, argFrom, argTo) {
return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo);
},
injection: injection
};
module.exports = EventPluginUtils;
}).call(exports, __webpack_require__(17));
}, /* 23 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactErrorUtils
*/
"use strict";
/**
* Call a function while guarding against errors that happens within it.
*
* @param {?String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} a First argument
* @param {*} b Second argument
*/
function invokeGuardedCallback(name, func, a, b) {
try {
return func(a, b);
} catch (x) {
return void (null === caughtError && (caughtError = x));
}
}
var caughtError = null, ReactErrorUtils = {
invokeGuardedCallback: invokeGuardedCallback,
/**
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
* handler are sure to be rethrown by rethrowCaughtError.
*/
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
rethrowCaughtError: function() {
if (caughtError) {
var error = caughtError;
throw caughtError = null, error;
}
}
};
if ("production" !== process.env.NODE_ENV && "undefined" != typeof window && "function" == typeof window.dispatchEvent && "undefined" != typeof document && "function" == typeof document.createEvent) {
var fakeNode = document.createElement("react");
ReactErrorUtils.invokeGuardedCallback = function(name, func, a, b) {
var boundFunc = func.bind(null, a, b), evtType = "react-" + name;
fakeNode.addEventListener(evtType, boundFunc, !1);
var evt = document.createEvent("Event");
evt.initEvent(evtType, !1, !1), fakeNode.dispatchEvent(evt), fakeNode.removeEventListener(evtType, boundFunc, !1);
};
}
module.exports = ReactErrorUtils;
}).call(exports, __webpack_require__(17));
}, /* 24 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
"use strict";
var emptyFunction = __webpack_require__(25), warning = emptyFunction;
"production" !== process.env.NODE_ENV && (warning = function(condition, format) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _len > _key; _key++) args[_key - 2] = arguments[_key];
if (void 0 === format) throw new Error("`warning(condition, format, ...args)` requires a warning message argument");
if (0 !== format.indexOf("Failed Composite propType: ") && !condition) {
var argIndex = 0, message = "Warning: " + format.replace(/%s/g, function() {
return args[argIndex++];
});
"undefined" != typeof console && console.error(message);
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
}
}), module.exports = warning;
}).call(exports, __webpack_require__(17));
}, /* 25 */
/***/
function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function() {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function() {};
emptyFunction.thatReturns = makeEmptyFunction, emptyFunction.thatReturnsFalse = makeEmptyFunction(!1),
emptyFunction.thatReturnsTrue = makeEmptyFunction(!0), emptyFunction.thatReturnsNull = makeEmptyFunction(null),
emptyFunction.thatReturnsThis = function() {
return this;
}, emptyFunction.thatReturnsArgument = function(arg) {
return arg;
}, module.exports = emptyFunction;
}, /* 26 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule accumulateInto
*/
"use strict";
/**
*
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
if (null == next ? "production" !== process.env.NODE_ENV ? invariant(!1, "accumulateInto(...): Accumulated items must not be null or undefined.") : invariant(!1) : void 0,
null == current) return next;
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current), nextIsArray = Array.isArray(next);
return currentIsArray && nextIsArray ? (current.push.apply(current, next), current) : currentIsArray ? (current.push(next),
current) : nextIsArray ? [ current ].concat(next) : [ current, next ];
}
var invariant = __webpack_require__(18);
module.exports = accumulateInto;
}).call(exports, __webpack_require__(17));
}, /* 27 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule forEachAccumulated
*/
"use strict";
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function(arr, cb, scope) {
Array.isArray(arr) ? arr.forEach(cb, scope) : arr && cb.call(scope, arr);
};
module.exports = forEachAccumulated;
}, /* 28 */
/***/
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 = !("undefined" == typeof window || !window.document || !window.document.createElement), ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: "undefined" != typeof Worker,
canUseEventListeners: canUseDOM && !(!window.addEventListener && !window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM
};
module.exports = ExecutionEnvironment;
}, /* 29 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule FallbackCompositionState
*/
"use strict";
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root, this._startText = this.getText(), this._fallbackText = null;
}
var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), getTextContentAccessor = __webpack_require__(32);
_assign(FallbackCompositionState.prototype, {
destructor: function() {
this._root = null, this._startText = null, this._fallbackText = null;
},
/**
* Get current text of input.
*
* @return {string}
*/
getText: function() {
return "value" in this._root ? this._root.value : this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function() {
if (this._fallbackText) return this._fallbackText;
var start, end, startValue = this._startText, startLength = startValue.length, endValue = this.getText(), endLength = endValue.length;
for (start = 0; startLength > start && startValue[start] === endValue[start]; start++) ;
var minEnd = startLength - start;
for (end = 1; minEnd >= end && startValue[startLength - end] === endValue[endLength - end]; end++) ;
var sliceTail = end > 1 ? 1 - end : void 0;
return this._fallbackText = endValue.slice(start, sliceTail), this._fallbackText;
}
}), PooledClass.addPoolingTo(FallbackCompositionState), module.exports = FallbackCompositionState;
}, /* 30 */
/***/
function(module, exports) {
"use strict";
function toObject(val) {
if (null === val || void 0 === val) throw new TypeError("Object.assign cannot be called with null or undefined");
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) return !1;
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String("abc");
if (// eslint-disable-line
test1[5] = "de", "5" === Object.getOwnPropertyNames(test1)[0]) return !1;
for (var test2 = {}, i = 0; 10 > i; i++) test2["_" + String.fromCharCode(i)] = i;
var order2 = Object.getOwnPropertyNames(test2).map(function(n) {
return test2[n];
});
if ("0123456789" !== order2.join("")) return !1;
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
return "abcdefghijklmnopqrst".split("").forEach(function(letter) {
test3[letter] = letter;
}), "abcdefghijklmnopqrst" === Object.keys(Object.assign({}, test3)).join("");
} catch (e) {
// We don't expect any of the above to throw, but better to be safe.
return !1;
}
}
/* eslint-disable no-unused-vars */
var hasOwnProperty = Object.prototype.hasOwnProperty, propIsEnumerable = Object.prototype.propertyIsEnumerable;
module.exports = shouldUseNative() ? Object.assign : function(target, source) {
for (var from, symbols, to = toObject(target), s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) hasOwnProperty.call(from, key) && (to[key] = from[key]);
if (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) propIsEnumerable.call(from, symbols[i]) && (to[symbols[i]] = from[symbols[i]]);
}
}
return to;
};
}, /* 31 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PooledClass
*/
"use strict";
var invariant = __webpack_require__(18), oneArgumentPooler = function(copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, copyFieldsFrom), instance;
}
return new Klass(copyFieldsFrom);
}, twoArgumentPooler = function(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, a1, a2), instance;
}
return new Klass(a1, a2);
}, threeArgumentPooler = function(a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, a1, a2, a3), instance;
}
return new Klass(a1, a2, a3);
}, fourArgumentPooler = function(a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, a1, a2, a3, a4), instance;
}
return new Klass(a1, a2, a3, a4);
}, fiveArgumentPooler = function(a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
return Klass.call(instance, a1, a2, a3, a4, a5), instance;
}
return new Klass(a1, a2, a3, a4, a5);
}, standardReleaser = function(instance) {
var Klass = this;
instance instanceof Klass ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Trying to release an instance into a pool of a different type.") : invariant(!1),
instance.destructor(), Klass.instancePool.length < Klass.poolSize && Klass.instancePool.push(instance);
}, DEFAULT_POOL_SIZE = 10, DEFAULT_POOLER = oneArgumentPooler, addPoolingTo = function(CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
return NewKlass.instancePool = [], NewKlass.getPooled = pooler || DEFAULT_POOLER,
NewKlass.poolSize || (NewKlass.poolSize = DEFAULT_POOL_SIZE), NewKlass.release = standardReleaser,
NewKlass;
}, PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
}).call(exports, __webpack_require__(17));
}, /* 32 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getTextContentAccessor
*/
"use strict";
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
return !contentKey && ExecutionEnvironment.canUseDOM && (contentKey = "textContent" in document.documentElement ? "textContent" : "innerText"),
contentKey;
}
var ExecutionEnvironment = __webpack_require__(28), contentKey = null;
module.exports = getTextContentAccessor;
}, /* 33 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticCompositionEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticEvent = __webpack_require__(34), CompositionEventInterface = {
data: null
};
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface),
module.exports = SyntheticCompositionEvent;
}, /* 34 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticEvent
*/
"use strict";
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {*} targetInst Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @param {DOMEventTarget} nativeEventTarget Target node.
*/
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
"production" !== process.env.NODE_ENV && (delete this.nativeEvent, delete this.preventDefault,
delete this.stopPropagation), this.dispatchConfig = dispatchConfig, this._targetInst = targetInst,
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) if (Interface.hasOwnProperty(propName)) {
"production" !== process.env.NODE_ENV && delete this[propName];
var normalize = Interface[propName];
normalize ? this[propName] = normalize(nativeEvent) : "target" === propName ? this.target = nativeEventTarget : this[propName] = nativeEvent[propName];
}
var defaultPrevented = null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : nativeEvent.returnValue === !1;
return defaultPrevented ? this.isDefaultPrevented = emptyFunction.thatReturnsTrue : this.isDefaultPrevented = emptyFunction.thatReturnsFalse,
this.isPropagationStopped = emptyFunction.thatReturnsFalse, this;
}
/**
* Helper to nullify syntheticEvent instance properties when destructing
*
* @param {object} SyntheticEvent
* @param {String} propName
* @return {object} defineProperty object
*/
function getPooledWarningPropertyDefinition(propName, getVal) {
function set(val) {
var action = isFunction ? "setting the method" : "setting the property";
return warn(action, "This is effectively a no-op"), val;
}
function get() {
var action = isFunction ? "accessing the method" : "accessing the property", result = isFunction ? "This is a no-op function" : "This is set to null";
return warn(action, result), getVal;
}
function warn(action, result) {
var warningCondition = !1;
"production" !== process.env.NODE_ENV ? warning(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, you're %s `%s` on a released/nullified synthetic event. %s. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.", action, propName, result) : void 0;
}
var isFunction = "function" == typeof getVal;
return {
configurable: !0,
set: set,
get: get
};
}
var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), emptyFunction = __webpack_require__(25), warning = __webpack_require__(24), didWarnForAddedNewProperty = !1, isProxySupported = "function" == typeof Proxy, shouldBeReleasedProperties = [ "dispatchConfig", "_targetInst", "nativeEvent", "isDefaultPrevented", "isPropagationStopped", "_dispatchListeners", "_dispatchInstances" ], EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function(event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
_assign(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = !0;
var event = this.nativeEvent;
event && (event.preventDefault ? event.preventDefault() : event.returnValue = !1,
this.isDefaultPrevented = emptyFunction.thatReturnsTrue);
},
stopPropagation: function() {
var event = this.nativeEvent;
event && (event.stopPropagation ? event.stopPropagation() : event.cancelBubble = !0,
this.isPropagationStopped = emptyFunction.thatReturnsTrue);
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function() {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function() {
var Interface = this.constructor.Interface;
for (var propName in Interface) "production" !== process.env.NODE_ENV ? Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])) : this[propName] = null;
for (var i = 0; i < shouldBeReleasedProperties.length; i++) this[shouldBeReleasedProperties[i]] = null;
if ("production" !== process.env.NODE_ENV) {
var noop = __webpack_require__(25);
Object.defineProperty(this, "nativeEvent", getPooledWarningPropertyDefinition("nativeEvent", null)),
Object.defineProperty(this, "preventDefault", getPooledWarningPropertyDefinition("preventDefault", noop)),
Object.defineProperty(this, "stopPropagation", getPooledWarningPropertyDefinition("stopPropagation", noop));
}
}
}), SyntheticEvent.Interface = EventInterface, "production" !== process.env.NODE_ENV && isProxySupported && (/*eslint-disable no-func-assign */
SyntheticEvent = new Proxy(SyntheticEvent, {
construct: function(target, args) {
return this.apply(target, Object.create(target.prototype), args);
},
apply: function(constructor, that, args) {
return new Proxy(constructor.apply(that, args), {
set: function(target, prop, value) {
return "isPersistent" === prop || target.constructor.Interface.hasOwnProperty(prop) || -1 !== shouldBeReleasedProperties.indexOf(prop) || ("production" !== process.env.NODE_ENV ? warning(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're seeing this, you're adding a new property in the synthetic event object. The property is never released. See https://fb.me/react-event-pooling for more information.") : void 0,
didWarnForAddedNewProperty = !0), target[prop] = value, !0;
}
});
}
})), /**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function(Class, Interface) {
var Super = this, E = function() {};
E.prototype = Super.prototype;
var prototype = new E();
_assign(prototype, Class.prototype), Class.prototype = prototype, Class.prototype.constructor = Class,
Class.Interface = _assign({}, Super.Interface, Interface), Class.augmentClass = Super.augmentClass,
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
}, PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler), module.exports = SyntheticEvent;
}).call(exports, __webpack_require__(17));
}, /* 35 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticInputEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticEvent = __webpack_require__(34), InputEventInterface = {
data: null
};
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface), module.exports = SyntheticInputEvent;
}, /* 36 */
/***/
function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) if (oneKeyObj.hasOwnProperty(key)) return key;
return null;
};
module.exports = keyOf;
}, /* 37 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ChangeEventPlugin
*/
"use strict";
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return "select" === nodeName || "input" === nodeName && "file" === elem.type;
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
EventPropagators.accumulateTwoPhaseDispatches(event), // If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event), EventPluginHub.processEventQueue(!1);
}
function startWatchingForChangeEventIE8(target, targetInst) {
activeElement = target, activeElementInst = targetInst, activeElement.attachEvent("onchange", manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
activeElement && (activeElement.detachEvent("onchange", manualDispatchChangeEvent),
activeElement = null, activeElementInst = null);
}
function getTargetInstForChangeEvent(topLevelType, targetInst) {
return topLevelType === topLevelTypes.topChange ? targetInst : void 0;
}
function handleEventsForChangeEventIE8(topLevelType, target, targetInst) {
topLevelType === topLevelTypes.topFocus ? (// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8(), startWatchingForChangeEventIE8(target, targetInst)) : topLevelType === topLevelTypes.topBlur && stopWatchingForChangeEventIE8();
}
/**
* (For IE <=11) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetInst) {
activeElement = target, activeElementInst = targetInst, activeElementValue = target.value,
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, "value"),
Object.defineProperty(activeElement, "value", newValueProp), activeElement.attachEvent ? activeElement.attachEvent("onpropertychange", handlePropertyChange) : activeElement.addEventListener("propertychange", handlePropertyChange, !1);
}
/**
* (For IE <=11) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
activeElement && (// delete restores the original property definition
delete activeElement.value, activeElement.detachEvent ? activeElement.detachEvent("onpropertychange", handlePropertyChange) : activeElement.removeEventListener("propertychange", handlePropertyChange, !1),
activeElement = null, activeElementInst = null, activeElementValue = null, activeElementValueProp = null);
}
/**
* (For IE <=11) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if ("value" === nativeEvent.propertyName) {
var value = nativeEvent.srcElement.value;
value !== activeElementValue && (activeElementValue = value, manualDispatchChangeEvent(nativeEvent));
}
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetInstForInputEvent(topLevelType, targetInst) {
return topLevelType === topLevelTypes.topInput ? targetInst : void 0;
}
function handleEventsForInputEventIE(topLevelType, target, targetInst) {
topLevelType === topLevelTypes.topFocus ? (// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9-11, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange(), startWatchingForValueChange(target, targetInst)) : topLevelType === topLevelTypes.topBlur && stopWatchingForValueChange();
}
// For IE8 and IE9.
function getTargetInstForInputEventIE(topLevelType, targetInst) {
return topLevelType !== topLevelTypes.topSelectionChange && topLevelType !== topLevelTypes.topKeyUp && topLevelType !== topLevelTypes.topKeyDown || !activeElement || activeElement.value === activeElementValue ? void 0 : (activeElementValue = activeElement.value,
activeElementInst);
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return elem.nodeName && "input" === elem.nodeName.toLowerCase() && ("checkbox" === elem.type || "radio" === elem.type);
}
function getTargetInstForClickEvent(topLevelType, targetInst) {
return topLevelType === topLevelTypes.topClick ? targetInst : void 0;
}
var EventConstants = __webpack_require__(15), EventPluginHub = __webpack_require__(20), EventPropagators = __webpack_require__(19), ExecutionEnvironment = __webpack_require__(28), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), SyntheticEvent = __webpack_require__(34), getEventTarget = __webpack_require__(55), isEventSupported = __webpack_require__(56), isTextInputElement = __webpack_require__(57), keyOf = __webpack_require__(36), topLevelTypes = EventConstants.topLevelTypes, eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({
onChange: null
}),
captured: keyOf({
onChangeCapture: null
})
},
dependencies: [ topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange ]
}
}, activeElement = null, activeElementInst = null, activeElementValue = null, activeElementValueProp = null, doesChangeEventBubble = !1;
ExecutionEnvironment.canUseDOM && (// See `handleChange` comment below
doesChangeEventBubble = isEventSupported("change") && (!("documentMode" in document) || document.documentMode > 8));
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = !1;
ExecutionEnvironment.canUseDOM && (// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events.
// IE10+ fire input events to often, such when a placeholder
// changes or when an input with a placeholder is focused.
isInputEventSupported = isEventSupported("input") && (!("documentMode" in document) || document.documentMode > 11));
/**
* (For IE <=11) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function() {
return activeElementValueProp.get.call(this);
},
set: function(val) {
activeElementValue = "" + val, activeElementValueProp.set.call(this, val);
}
}, ChangeEventPlugin = {
eventTypes: eventTypes,
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var getTargetInstFunc, handleEventFunc, targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
if (shouldUseChangeEvent(targetNode) ? doesChangeEventBubble ? getTargetInstFunc = getTargetInstForChangeEvent : handleEventFunc = handleEventsForChangeEventIE8 : isTextInputElement(targetNode) ? isInputEventSupported ? getTargetInstFunc = getTargetInstForInputEvent : (getTargetInstFunc = getTargetInstForInputEventIE,
handleEventFunc = handleEventsForInputEventIE) : shouldUseClickEvent(targetNode) && (getTargetInstFunc = getTargetInstForClickEvent),
getTargetInstFunc) {
var inst = getTargetInstFunc(topLevelType, targetInst);
if (inst) {
var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget);
return event.type = "change", EventPropagators.accumulateTwoPhaseDispatches(event),
event;
}
}
handleEventFunc && handleEventFunc(topLevelType, targetNode, targetInst);
}
};
module.exports = ChangeEventPlugin;
}, /* 38 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponentTree
*/
"use strict";
/**
* Drill down (through composites and empty components) until we get a native or
* native text component.
*
* This is pretty polymorphic but unavoidable with the current structure we have
* for `_renderedChildren`.
*/
function getRenderedNativeOrTextFromComponent(component) {
for (var rendered; rendered = component._renderedComponent; ) component = rendered;
return component;
}
/**
* Populate `_nativeNode` on the rendered native/text component with the given
* DOM node. The passed `inst` can be a composite.
*/
function precacheNode(inst, node) {
var nativeInst = getRenderedNativeOrTextFromComponent(inst);
nativeInst._nativeNode = node, node[internalInstanceKey] = nativeInst;
}
function uncacheNode(inst) {
var node = inst._nativeNode;
node && (delete node[internalInstanceKey], inst._nativeNode = null);
}
/**
* Populate `_nativeNode` on each child of `inst`, assuming that the children
* match up with the DOM (element) children of `node`.
*
* We cache entire levels at once to avoid an n^2 problem where we access the
* children of a node sequentially and have to walk from the start to our target
* node every time.
*
* Since we update `_renderedChildren` and the actual DOM at (slightly)
* different times, we could race here and see a newer `_renderedChildren` than
* the DOM nodes we see. To avoid this, ReactMultiChild calls
* `prepareToManageChildren` before we change `_renderedChildren`, at which
* time the container's child nodes are always cached (until it unmounts).
*/
function precacheChildNodes(inst, node) {
if (!(inst._flags & Flags.hasCachedChildNodes)) {
var children = inst._renderedChildren, childNode = node.firstChild;
outer: for (var name in children) if (children.hasOwnProperty(name)) {
var childInst = children[name], childID = getRenderedNativeOrTextFromComponent(childInst)._domID;
if (null != childID) {
// We assume the child nodes are in the same order as the child instances.
for (;null !== childNode; childNode = childNode.nextSibling) if (1 === childNode.nodeType && childNode.getAttribute(ATTR_NAME) === String(childID) || 8 === childNode.nodeType && childNode.nodeValue === " react-text: " + childID + " " || 8 === childNode.nodeType && childNode.nodeValue === " react-empty: " + childID + " ") {
precacheNode(childInst, childNode);
continue outer;
}
"production" !== process.env.NODE_ENV ? invariant(!1, "Unable to find element with ID %s.", childID) : invariant(!1);
}
}
inst._flags |= Flags.hasCachedChildNodes;
}
}
/**
* Given a DOM node, return the closest ReactDOMComponent or
* ReactDOMTextComponent instance ancestor.
*/
function getClosestInstanceFromNode(node) {
if (node[internalInstanceKey]) return node[internalInstanceKey];
for (// Walk up the tree until we find an ancestor whose instance we have cached.
var parents = []; !node[internalInstanceKey]; ) {
if (parents.push(node), !node.parentNode) // Top of the tree. This node must not be part of a React tree (or is
// unmounted, potentially).
return null;
node = node.parentNode;
}
for (var closest, inst; node && (inst = node[internalInstanceKey]); node = parents.pop()) closest = inst,
parents.length && precacheChildNodes(inst, node);
return closest;
}
/**
* Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
* instance, or null if the node was not rendered by this React.
*/
function getInstanceFromNode(node) {
var inst = getClosestInstanceFromNode(node);
return null != inst && inst._nativeNode === node ? inst : null;
}
/**
* Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
* DOM node.
*/
function getNodeFromInstance(inst) {
if (void 0 === inst._nativeNode ? "production" !== process.env.NODE_ENV ? invariant(!1, "getNodeFromInstance: Invalid argument.") : invariant(!1) : void 0,
inst._nativeNode) return inst._nativeNode;
for (// Walk up the tree until we find an ancestor whose DOM node we have cached.
var parents = []; !inst._nativeNode; ) parents.push(inst), inst._nativeParent ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "React DOM tree root should always have a node reference.") : invariant(!1),
inst = inst._nativeParent;
// Now parents contains each ancestor that does *not* have a cached native
// node, and `inst` is the deepest ancestor that does.
for (;parents.length; inst = parents.pop()) precacheChildNodes(inst, inst._nativeNode);
return inst._nativeNode;
}
var DOMProperty = __webpack_require__(39), ReactDOMComponentFlags = __webpack_require__(40), invariant = __webpack_require__(18), ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME, Flags = ReactDOMComponentFlags, internalInstanceKey = "__reactInternalInstance$" + Math.random().toString(36).slice(2), ReactDOMComponentTree = {
getClosestInstanceFromNode: getClosestInstanceFromNode,
getInstanceFromNode: getInstanceFromNode,
getNodeFromInstance: getNodeFromInstance,
precacheChildNodes: precacheChildNodes,
precacheNode: precacheNode,
uncacheNode: uncacheNode
};
module.exports = ReactDOMComponentTree;
}).call(exports, __webpack_require__(17));
}, /* 39 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMProperty
*/
"use strict";
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var invariant = __webpack_require__(18), DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_PROPERTY: 1,
HAS_SIDE_EFFECTS: 2,
HAS_BOOLEAN_VALUE: 4,
HAS_NUMERIC_VALUE: 8,
HAS_POSITIVE_NUMERIC_VALUE: 24,
HAS_OVERLOADED_BOOLEAN_VALUE: 32,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
* attribute namespace URL. (Attribute names not specified use no namespace.)
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function(domPropertyConfig) {
var Injection = DOMPropertyInjection, Properties = domPropertyConfig.Properties || {}, DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}, DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}, DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}, DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
domPropertyConfig.isCustomAttribute && DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
for (var propName in Properties) {
DOMProperty.properties.hasOwnProperty(propName) ? "production" !== process.env.NODE_ENV ? invariant(!1, "injectDOMPropertyConfig(...): You're trying to inject DOM property '%s' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.", propName) : invariant(!1) : void 0;
var lowerCased = propName.toLowerCase(), propConfig = Properties[propName], propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS),
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
};
if (!propertyInfo.mustUseProperty && propertyInfo.hasSideEffects ? "production" !== process.env.NODE_ENV ? invariant(!1, "DOMProperty: Properties that have side effects must use property: %s", propName) : invariant(!1) : void 0,
propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1 ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s", propName) : invariant(!1),
"production" !== process.env.NODE_ENV && (DOMProperty.getPossibleStandardName[lowerCased] = propName),
DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
propertyInfo.attributeName = attributeName, "production" !== process.env.NODE_ENV && (DOMProperty.getPossibleStandardName[attributeName] = propName);
}
DOMAttributeNamespaces.hasOwnProperty(propName) && (propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]),
DOMPropertyNames.hasOwnProperty(propName) && (propertyInfo.propertyName = DOMPropertyNames[propName]),
DOMMutationMethods.hasOwnProperty(propName) && (propertyInfo.mutationMethod = DOMMutationMethods[propName]),
DOMProperty.properties[propName] = propertyInfo;
}
}
}, ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", DOMProperty = {
ID_ATTRIBUTE_NAME: "data-reactid",
ROOT_ATTRIBUTE_NAME: "data-reactroot",
ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040",
/**
* Map from property "standard name" to an object with info about how to set
* the property in the DOM. Each object contains:
*
* attributeName:
* Used when rendering markup or with `*Attribute()`.
* attributeNamespace
* propertyName:
* Used on DOM node instances. (This includes properties that mutate due to
* external factors.)
* mutationMethod:
* If non-null, used instead of the property or `setAttribute()` after
* initial render.
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* hasSideEffects:
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. If true, we read from
* the DOM before updating to ensure that the value is only set if it has
* changed.
* hasBooleanValue:
* Whether the property should be removed when set to a falsey value.
* hasNumericValue:
* Whether the property must be numeric or parse as a numeric and should be
* removed when set to a falsey value.
* hasPositiveNumericValue:
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* hasOverloadedBooleanValue:
* Whether the property can be used as a flag as well as with a value.
* Removed when strictly equal to false; present without a value when
* strictly equal to true; present with a value otherwise.
*/
properties: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties. Available only in __DEV__.
* @type {Object}
*/
getPossibleStandardName: "production" !== process.env.NODE_ENV ? {} : null,
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function(attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) return !0;
}
return !1;
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
}).call(exports, __webpack_require__(17));
}, /* 40 */
/***/
function(module, exports) {
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponentFlags
*/
"use strict";
var ReactDOMComponentFlags = {
hasCachedChildNodes: 1
};
module.exports = ReactDOMComponentFlags;
}, /* 41 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdates
*/
"use strict";
function ensureInjected() {
ReactUpdates.ReactReconcileTransaction && batchingStrategy ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must inject a reconcile transaction class and batching strategy") : invariant(!1);
}
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction(), this.dirtyComponentsLength = null, this.callbackQueue = CallbackQueue.getPooled(),
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(/* useCreateElement */
!0);
}
function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected(), batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
len !== dirtyComponents.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected flush transaction's stored dirty-components length (%s) to match dirty-components array length (%s).", len, dirtyComponents.length) : invariant(!1) : void 0,
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator), // Any updates enqueued while reconciling must be performed after this entire
// batch. Otherwise, if dirtyComponents is [A, B] where A has children B and
// C, B could update twice in a single batch if C's render enqueues an update
// to B (since B would have already updated, we should skip it, and the only
// way we can know to do so is by checking the batch counter).
updateBatchNumber++;
for (var i = 0; len > i; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i], callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var namedComponent = component;
// Duck type TopLevelWrapper. This is probably always true.
component._currentElement.props === component._renderedComponent._currentElement && (namedComponent = component._renderedComponent),
markerName = "React update: " + namedComponent.getName(), console.time(markerName);
}
if (ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber),
markerName && console.timeEnd(markerName), callbacks) for (var j = 0; j < callbacks.length; j++) transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
}
}
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
return ensureInjected(), batchingStrategy.isBatchingUpdates ? (dirtyComponents.push(component),
void (null == component._updateBatchNumber && (component._updateBatchNumber = updateBatchNumber + 1))) : void batchingStrategy.batchedUpdates(enqueueUpdate, component);
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
batchingStrategy.isBatchingUpdates ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates.asap: Can't enqueue an asap callback in a context whereupdates are not being batched.") : invariant(!1),
asapCallbackQueue.enqueue(callback, context), asapEnqueued = !0;
}
var _assign = __webpack_require__(30), CallbackQueue = __webpack_require__(42), PooledClass = __webpack_require__(31), ReactFeatureFlags = __webpack_require__(43), ReactInstrumentation = __webpack_require__(44), ReactReconciler = __webpack_require__(51), Transaction = __webpack_require__(54), invariant = __webpack_require__(18), dirtyComponents = [], updateBatchNumber = 0, asapCallbackQueue = CallbackQueue.getPooled(), asapEnqueued = !1, batchingStrategy = null, NESTED_UPDATES = {
initialize: function() {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function() {
this.dirtyComponentsLength !== dirtyComponents.length ? (// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength), flushBatchedUpdates()) : dirtyComponents.length = 0;
}
}, UPDATE_QUEUEING = {
initialize: function() {
this.callbackQueue.reset();
},
close: function() {
this.callbackQueue.notifyAll();
}
}, TRANSACTION_WRAPPERS = [ NESTED_UPDATES, UPDATE_QUEUEING ];
_assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
destructor: function() {
this.dirtyComponentsLength = null, CallbackQueue.release(this.callbackQueue), this.callbackQueue = null,
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction), this.reconcileTransaction = null;
},
perform: function(method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
}), PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
var flushBatchedUpdates = function() {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
for ("production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onBeginFlush(); dirtyComponents.length || asapEnqueued; ) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction), ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = !1;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled(), queue.notifyAll(), CallbackQueue.release(queue);
}
}
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onEndFlush();
}, ReactUpdatesInjection = {
injectReconcileTransaction: function(ReconcileTransaction) {
ReconcileTransaction ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide a reconcile transaction class") : invariant(!1),
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function(_batchingStrategy) {
_batchingStrategy ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide a batching strategy") : invariant(!1),
"function" != typeof _batchingStrategy.batchedUpdates ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide a batchedUpdates() function") : invariant(!1) : void 0,
"boolean" != typeof _batchingStrategy.isBatchingUpdates ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactUpdates: must provide an isBatchingUpdates boolean attribute") : invariant(!1) : void 0,
batchingStrategy = _batchingStrategy;
}
}, ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
}).call(exports, __webpack_require__(17));
}, /* 42 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CallbackQueue
*/
"use strict";
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null, this._contexts = null;
}
var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), invariant = __webpack_require__(18);
_assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function(callback, context) {
this._callbacks = this._callbacks || [], this._contexts = this._contexts || [],
this._callbacks.push(callback), this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function() {
var callbacks = this._callbacks, contexts = this._contexts;
if (callbacks) {
callbacks.length !== contexts.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Mismatched list of contexts in callback queue") : invariant(!1) : void 0,
this._callbacks = null, this._contexts = null;
for (var i = 0; i < callbacks.length; i++) callbacks[i].call(contexts[i]);
callbacks.length = 0, contexts.length = 0;
}
},
checkpoint: function() {
return this._callbacks ? this._callbacks.length : 0;
},
rollback: function(len) {
this._callbacks && (this._callbacks.length = len, this._contexts.length = len);
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function() {
this._callbacks = null, this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function() {
this.reset();
}
}), PooledClass.addPoolingTo(CallbackQueue), module.exports = CallbackQueue;
}).call(exports, __webpack_require__(17));
}, /* 43 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactFeatureFlags
*/
"use strict";
var ReactFeatureFlags = {
// When true, call console.time() before and .timeEnd() after each top-level
// render (both initial renders and updates). Useful when looking at prod-mode
// timeline profiles in Chrome, for example.
logTopLevelRenders: !1
};
module.exports = ReactFeatureFlags;
}, /* 44 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstrumentation
*/
"use strict";
var ReactDebugTool = __webpack_require__(45);
module.exports = {
debugTool: ReactDebugTool
};
}, /* 45 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDebugTool
*/
"use strict";
function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
"production" !== process.env.NODE_ENV && eventHandlers.forEach(function(handler) {
try {
handler[handlerFunctionName] && handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5);
} catch (e) {
"production" !== process.env.NODE_ENV ? warning(!handlerDoesThrowForEvent[handlerFunctionName], "exception thrown by devtool while handling %s: %s", handlerFunctionName, e.message) : void 0,
handlerDoesThrowForEvent[handlerFunctionName] = !0;
}
});
}
function clearHistory() {
ReactComponentTreeDevtool.purgeUnmountedComponents(), ReactNativeOperationHistoryDevtool.clearHistory();
}
function getTreeSnapshot(registeredIDs) {
return registeredIDs.reduce(function(tree, id) {
var ownerID = ReactComponentTreeDevtool.getOwnerID(id), parentID = ReactComponentTreeDevtool.getParentID(id);
return tree[id] = {
displayName: ReactComponentTreeDevtool.getDisplayName(id),
text: ReactComponentTreeDevtool.getText(id),
updateCount: ReactComponentTreeDevtool.getUpdateCount(id),
childIDs: ReactComponentTreeDevtool.getChildIDs(id),
// Text nodes don't have owners but this is close enough.
ownerID: ownerID || ReactComponentTreeDevtool.getOwnerID(parentID),
parentID: parentID
}, tree;
}, {});
}
function resetMeasurements() {
if ("production" !== process.env.NODE_ENV) {
var previousStartTime = currentFlushStartTime, previousMeasurements = currentFlushMeasurements || [], previousOperations = ReactNativeOperationHistoryDevtool.getHistory();
if (!isProfiling || 0 === currentFlushNesting) return currentFlushStartTime = null,
currentFlushMeasurements = null, void clearHistory();
if (previousMeasurements.length || previousOperations.length) {
var registeredIDs = ReactComponentTreeDevtool.getRegisteredIDs();
flushHistory.push({
duration: performanceNow() - previousStartTime,
measurements: previousMeasurements || [],
operations: previousOperations || [],
treeSnapshot: getTreeSnapshot(registeredIDs)
});
}
clearHistory(), currentFlushStartTime = performanceNow(), currentFlushMeasurements = [];
}
}
function checkDebugID(debugID) {
"production" !== process.env.NODE_ENV ? warning(debugID, "ReactDebugTool: debugID may not be empty.") : void 0;
}
var ExecutionEnvironment = __webpack_require__(28), performanceNow = __webpack_require__(46), warning = __webpack_require__(24), eventHandlers = [], handlerDoesThrowForEvent = {}, isProfiling = !1, flushHistory = [], currentFlushNesting = 0, currentFlushMeasurements = null, currentFlushStartTime = null, currentTimerDebugID = null, currentTimerStartTime = null, currentTimerType = null, ReactDebugTool = {
addDevtool: function(devtool) {
eventHandlers.push(devtool);
},
removeDevtool: function(devtool) {
for (var i = 0; i < eventHandlers.length; i++) eventHandlers[i] === devtool && (eventHandlers.splice(i, 1),
i--);
},
beginProfiling: function() {
if ("production" !== process.env.NODE_ENV) {
if (isProfiling) return;
isProfiling = !0, flushHistory.length = 0, resetMeasurements();
}
},
endProfiling: function() {
if ("production" !== process.env.NODE_ENV) {
if (!isProfiling) return;
isProfiling = !1, resetMeasurements();
}
},
getFlushHistory: function() {
return "production" !== process.env.NODE_ENV ? flushHistory : void 0;
},
onBeginFlush: function() {
"production" !== process.env.NODE_ENV && (currentFlushNesting++, resetMeasurements()),
emitEvent("onBeginFlush");
},
onEndFlush: function() {
"production" !== process.env.NODE_ENV && (resetMeasurements(), currentFlushNesting--),
emitEvent("onEndFlush");
},
onBeginLifeCycleTimer: function(debugID, timerType) {
checkDebugID(debugID), emitEvent("onBeginLifeCycleTimer", debugID, timerType), "production" !== process.env.NODE_ENV && isProfiling && currentFlushNesting > 0 && ("production" !== process.env.NODE_ENV ? warning(!currentTimerType, "There is an internal error in the React performance measurement code. Did not expect %s timer to start while %s timer is still in progress for %s instance.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another") : void 0,
currentTimerStartTime = performanceNow(), currentTimerDebugID = debugID, currentTimerType = timerType);
},
onEndLifeCycleTimer: function(debugID, timerType) {
checkDebugID(debugID), "production" !== process.env.NODE_ENV && isProfiling && currentFlushNesting > 0 && ("production" !== process.env.NODE_ENV ? warning(currentTimerType === timerType, "There is an internal error in the React performance measurement code. We did not expect %s timer to stop while %s timer is still in progress for %s instance. Please report this as a bug in React.", timerType, currentTimerType || "no", debugID === currentTimerDebugID ? "the same" : "another") : void 0,
currentFlushMeasurements.push({
timerType: timerType,
instanceID: debugID,
duration: performanceNow() - currentTimerStartTime
}), currentTimerStartTime = null, currentTimerDebugID = null, currentTimerType = null),
emitEvent("onEndLifeCycleTimer", debugID, timerType);
},
onBeginReconcilerTimer: function(debugID, timerType) {
checkDebugID(debugID), emitEvent("onBeginReconcilerTimer", debugID, timerType);
},
onEndReconcilerTimer: function(debugID, timerType) {
checkDebugID(debugID), emitEvent("onEndReconcilerTimer", debugID, timerType);
},
onBeginProcessingChildContext: function() {
emitEvent("onBeginProcessingChildContext");
},
onEndProcessingChildContext: function() {
emitEvent("onEndProcessingChildContext");
},
onNativeOperation: function(debugID, type, payload) {
checkDebugID(debugID), emitEvent("onNativeOperation", debugID, type, payload);
},
onSetState: function() {
emitEvent("onSetState");
},
onSetDisplayName: function(debugID, displayName) {
checkDebugID(debugID), emitEvent("onSetDisplayName", debugID, displayName);
},
onSetChildren: function(debugID, childDebugIDs) {
checkDebugID(debugID), emitEvent("onSetChildren", debugID, childDebugIDs);
},
onSetOwner: function(debugID, ownerDebugID) {
checkDebugID(debugID), emitEvent("onSetOwner", debugID, ownerDebugID);
},
onSetText: function(debugID, text) {
checkDebugID(debugID), emitEvent("onSetText", debugID, text);
},
onMountRootComponent: function(debugID) {
checkDebugID(debugID), emitEvent("onMountRootComponent", debugID);
},
onMountComponent: function(debugID) {
checkDebugID(debugID), emitEvent("onMountComponent", debugID);
},
onUpdateComponent: function(debugID) {
checkDebugID(debugID), emitEvent("onUpdateComponent", debugID);
},
onUnmountComponent: function(debugID) {
checkDebugID(debugID), emitEvent("onUnmountComponent", debugID);
}
};
if ("production" !== process.env.NODE_ENV) {
var ReactInvalidSetStateWarningDevTool = __webpack_require__(48), ReactNativeOperationHistoryDevtool = __webpack_require__(49), ReactComponentTreeDevtool = __webpack_require__(50);
ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool), ReactDebugTool.addDevtool(ReactComponentTreeDevtool),
ReactDebugTool.addDevtool(ReactNativeOperationHistoryDevtool);
var url = ExecutionEnvironment.canUseDOM && window.location.href || "";
/[?&]react_perf\b/.test(url) && ReactDebugTool.beginProfiling();
}
module.exports = ReactDebugTool;
}).call(exports, __webpack_require__(17));
}, /* 46 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var performanceNow, performance = __webpack_require__(47);
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
performanceNow = performance.now ? function() {
return performance.now();
} : function() {
return Date.now();
}, module.exports = performanceNow;
}, /* 47 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
"use strict";
var performance, ExecutionEnvironment = __webpack_require__(28);
ExecutionEnvironment.canUseDOM && (performance = window.performance || window.msPerformance || window.webkitPerformance),
module.exports = performance || {};
}, /* 48 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInvalidSetStateWarningDevTool
*/
"use strict";
var warning = __webpack_require__(24);
if ("production" !== process.env.NODE_ENV) var processingChildContext = !1, warnInvalidSetState = function() {
"production" !== process.env.NODE_ENV ? warning(!processingChildContext, "setState(...): Cannot call setState() inside getChildContext()") : void 0;
};
var ReactInvalidSetStateWarningDevTool = {
onBeginProcessingChildContext: function() {
processingChildContext = !0;
},
onEndProcessingChildContext: function() {
processingChildContext = !1;
},
onSetState: function() {
warnInvalidSetState();
}
};
module.exports = ReactInvalidSetStateWarningDevTool;
}).call(exports, __webpack_require__(17));
}, /* 49 */
/***/
function(module, exports) {
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeOperationHistoryDevtool
*/
"use strict";
var history = [], ReactNativeOperationHistoryDevtool = {
onNativeOperation: function(debugID, type, payload) {
history.push({
instanceID: debugID,
type: type,
payload: payload
});
},
clearHistory: function() {
ReactNativeOperationHistoryDevtool._preventClearing || (history = []);
},
getHistory: function() {
return history;
}
};
module.exports = ReactNativeOperationHistoryDevtool;
}, /* 50 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentTreeDevtool
*/
"use strict";
function updateTree(id, update) {
tree[id] || (tree[id] = {
parentID: null,
ownerID: null,
text: null,
childIDs: [],
displayName: "Unknown",
isMounted: !1,
updateCount: 0
}), update(tree[id]);
}
function purgeDeep(id) {
var item = tree[id];
if (item) {
var childIDs = item.childIDs;
delete tree[id], childIDs.forEach(purgeDeep);
}
}
var invariant = __webpack_require__(18), tree = {}, rootIDs = [], ReactComponentTreeDevtool = {
onSetDisplayName: function(id, displayName) {
updateTree(id, function(item) {
return item.displayName = displayName;
});
},
onSetChildren: function(id, nextChildIDs) {
updateTree(id, function(item) {
var prevChildIDs = item.childIDs;
item.childIDs = nextChildIDs, nextChildIDs.forEach(function(nextChildID) {
var nextChild = tree[nextChildID];
nextChild ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Expected devtool events to fire for the child before its parent includes it in onSetChildren().") : invariant(!1),
null == nextChild.displayName ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected onSetDisplayName() to fire for the child before its parent includes it in onSetChildren().") : invariant(!1) : void 0,
null == nextChild.childIDs && null == nextChild.text ? "production" !== process.env.NODE_ENV ? invariant(!1, "Expected onSetChildren() or onSetText() to fire for the child before its parent includes it in onSetChildren().") : invariant(!1) : void 0,
nextChild.isMounted ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().") : invariant(!1),
-1 === prevChildIDs.indexOf(nextChildID) && (nextChild.parentID = id);
});
});
},
onSetOwner: function(id, ownerID) {
updateTree(id, function(item) {
return item.ownerID = ownerID;
});
},
onSetText: function(id, text) {
updateTree(id, function(item) {
return item.text = text;
});
},
onMountComponent: function(id) {
updateTree(id, function(item) {
return item.isMounted = !0;
});
},
onMountRootComponent: function(id) {
rootIDs.push(id);
},
onUpdateComponent: function(id) {
updateTree(id, function(item) {
return item.updateCount++;
});
},
onUnmountComponent: function(id) {
updateTree(id, function(item) {
return item.isMounted = !1;
}), rootIDs = rootIDs.filter(function(rootID) {
return rootID !== id;
});
},
purgeUnmountedComponents: function() {
ReactComponentTreeDevtool._preventPurging || Object.keys(tree).filter(function(id) {
return !tree[id].isMounted;
}).forEach(purgeDeep);
},
isMounted: function(id) {
var item = tree[id];
return item ? item.isMounted : !1;
},
getChildIDs: function(id) {
var item = tree[id];
return item ? item.childIDs : [];
},
getDisplayName: function(id) {
var item = tree[id];
return item ? item.displayName : "Unknown";
},
getOwnerID: function(id) {
var item = tree[id];
return item ? item.ownerID : null;
},
getParentID: function(id) {
var item = tree[id];
return item ? item.parentID : null;
},
getText: function(id) {
var item = tree[id];
return item ? item.text : null;
},
getUpdateCount: function(id) {
var item = tree[id];
return item ? item.updateCount : 0;
},
getRootIDs: function() {
return rootIDs;
},
getRegisteredIDs: function() {
return Object.keys(tree);
}
};
module.exports = ReactComponentTreeDevtool;
}).call(exports, __webpack_require__(17));
}, /* 51 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconciler
*/
"use strict";
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactRef = __webpack_require__(52), ReactInstrumentation = __webpack_require__(44), invariant = __webpack_require__(18), ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} the containing native component instance
* @param {?object} info about the native container
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function(internalInstance, transaction, nativeParent, nativeContainerInfo, context) {
"production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "mountComponent");
var markup = internalInstance.mountComponent(transaction, nativeParent, nativeContainerInfo, context);
return internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance),
"production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "mountComponent"),
ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID)), markup;
},
/**
* Returns a value that can be passed to
* ReactComponentEnvironment.replaceNodeWithMarkup.
*/
getNativeNode: function(internalInstance) {
return internalInstance.getNativeNode();
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function(internalInstance, safely) {
"production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "unmountComponent"),
ReactRef.detachRefs(internalInstance, internalInstance._currentElement), internalInstance.unmountComponent(safely),
"production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "unmountComponent"),
ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID));
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function(internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement !== prevElement || context !== internalInstance._context) {
"production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "receiveComponent");
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
refsChanged && ReactRef.detachRefs(internalInstance, prevElement), internalInstance.receiveComponent(nextElement, transaction, context),
refsChanged && internalInstance._currentElement && null != internalInstance._currentElement.ref && transaction.getReactMountReady().enqueue(attachRefs, internalInstance),
"production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "receiveComponent"),
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID));
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(internalInstance, transaction, updateBatchNumber) {
// The component's enqueued batch number should always be the current
// batch or the following one.
return internalInstance._updateBatchNumber !== updateBatchNumber ? void (null != internalInstance._updateBatchNumber && internalInstance._updateBatchNumber !== updateBatchNumber + 1 ? "production" !== process.env.NODE_ENV ? invariant(!1, "performUpdateIfNecessary: Unexpected batch number (current %s, pending %s)", updateBatchNumber, internalInstance._updateBatchNumber) : invariant(!1) : void 0) : ("production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && ReactInstrumentation.debugTool.onBeginReconcilerTimer(internalInstance._debugID, "performUpdateIfNecessary"),
internalInstance.performUpdateIfNecessary(transaction), void ("production" !== process.env.NODE_ENV && 0 !== internalInstance._debugID && (ReactInstrumentation.debugTool.onEndReconcilerTimer(internalInstance._debugID, "performUpdateIfNecessary"),
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID))));
}
};
module.exports = ReactReconciler;
}).call(exports, __webpack_require__(17));
}, /* 52 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactRef
*/
"use strict";
function attachRef(ref, component, owner) {
"function" == typeof ref ? ref(component.getPublicInstance()) : // Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
function detachRef(ref, component, owner) {
"function" == typeof ref ? ref(null) : // Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
var ReactOwner = __webpack_require__(53), ReactRef = {};
ReactRef.attachRefs = function(instance, element) {
if (null !== element && element !== !1) {
var ref = element.ref;
null != ref && attachRef(ref, instance, element._owner);
}
}, ReactRef.shouldUpdateRefs = function(prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
var prevEmpty = null === prevElement || prevElement === !1, nextEmpty = null === nextElement || nextElement === !1;
// This has a few false positives w/r/t empty components.
return prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref;
}, ReactRef.detachRefs = function(instance, element) {
if (null !== element && element !== !1) {
var ref = element.ref;
null != ref && detachRef(ref, instance, element._owner);
}
}, module.exports = ReactRef;
}, /* 53 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactOwner
*/
"use strict";
var invariant = __webpack_require__(18), ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function(object) {
return !(!object || "function" != typeof object.attachRef || "function" != typeof object.detachRef);
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function(component, ref, owner) {
ReactOwner.isValidOwner(owner) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).") : invariant(!1),
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function(component, ref, owner) {
ReactOwner.isValidOwner(owner) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).") : invariant(!1);
var ownerPublicInstance = owner.getPublicInstance();
// Check that `component`'s owner is still alive and that `component` is still the current ref
// because we do not want to detach the ref if another component stole it.
ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance() && owner.detachRef(ref);
}
};
module.exports = ReactOwner;
}).call(exports, __webpack_require__(17));
}, /* 54 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Transaction
*/
"use strict";
var invariant = __webpack_require__(18), 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(), this.wrapperInitData ? this.wrapperInitData.length = 0 : this.wrapperInitData = [],
this._isInTransaction = !1;
},
_isInTransaction: !1,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function() {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked. The optional arguments helps prevent the need
* to bind in many cases.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} a Argument to pass to the method.
* @param {Object?=} b Argument to pass to the method.
* @param {Object?=} c Argument to pass to the method.
* @param {Object?=} d Argument to pass to the method.
* @param {Object?=} e Argument to pass to the method.
* @param {Object?=} f Argument to pass to the method.
*
* @return {*} Return value from `method`.
*/
perform: function(method, scope, a, b, c, d, e, f) {
this.isInTransaction() ? "production" !== process.env.NODE_ENV ? invariant(!1, "Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.") : invariant(!1) : void 0;
var errorThrown, ret;
try {
this._isInTransaction = !0, // 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 = !0, this.initializeAll(0), ret = method.call(scope, a, b, c, d, e, f),
errorThrown = !1;
} 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 = !1;
}
}
return ret;
},
initializeAll: function(startIndex) {
for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR, this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) // The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function(startIndex) {
this.isInTransaction() ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Transaction.closeAll(): Cannot close transaction when none are open.") : invariant(!1);
for (var transactionWrappers = this.transactionWrappers, i = startIndex; i < transactionWrappers.length; i++) {
var errorThrown, wrapper = transactionWrappers[i], initData = this.wrapperInitData[i];
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 = !0, initData !== Transaction.OBSERVED_ERROR && wrapper.close && wrapper.close.call(this, initData),
errorThrown = !1;
} 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;
}
}, Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occurred.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
}).call(exports, __webpack_require__(17));
}, /* 55 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventTarget
*/
"use strict";
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
// Normalize SVG <use> element events #4963
return target.correspondingUseElement && (target = target.correspondingUseElement),
3 === target.nodeType ? target.parentNode : target;
}
module.exports = getEventTarget;
}, /* 56 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isEventSupported
*/
"use strict";
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !("addEventListener" in document)) return !1;
var eventName = "on" + eventNameSuffix, isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement("div");
element.setAttribute(eventName, "return;"), isSupported = "function" == typeof element[eventName];
}
// This is the only way to test support for the `wheel` event in IE9+.
return !isSupported && useHasFeature && "wheel" === eventNameSuffix && (isSupported = document.implementation.hasFeature("Events.wheel", "3.0")),
isSupported;
}
var useHasFeature, ExecutionEnvironment = __webpack_require__(28);
ExecutionEnvironment.canUseDOM && (useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature("", "") !== !0), module.exports = isEventSupported;
}, /* 57 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isTextInputElement
*/
"use strict";
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && ("input" === nodeName && supportedInputTypes[elem.type] || "textarea" === nodeName);
}
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
color: !0,
date: !0,
datetime: !0,
"datetime-local": !0,
email: !0,
month: !0,
number: !0,
password: !0,
range: !0,
search: !0,
tel: !0,
text: !0,
time: !0,
url: !0,
week: !0
};
module.exports = isTextInputElement;
}, /* 58 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DefaultEventPluginOrder
*/
"use strict";
var keyOf = __webpack_require__(36), DefaultEventPluginOrder = [ keyOf({
ResponderEventPlugin: null
}), keyOf({
SimpleEventPlugin: null
}), keyOf({
TapEventPlugin: null
}), keyOf({
EnterLeaveEventPlugin: null
}), keyOf({
ChangeEventPlugin: null
}), keyOf({
SelectEventPlugin: null
}), keyOf({
BeforeInputEventPlugin: null
}) ];
module.exports = DefaultEventPluginOrder;
}, /* 59 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EnterLeaveEventPlugin
*/
"use strict";
var EventConstants = __webpack_require__(15), EventPropagators = __webpack_require__(19), ReactDOMComponentTree = __webpack_require__(38), SyntheticMouseEvent = __webpack_require__(60), keyOf = __webpack_require__(36), topLevelTypes = EventConstants.topLevelTypes, eventTypes = {
mouseEnter: {
registrationName: keyOf({
onMouseEnter: null
}),
dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ]
},
mouseLeave: {
registrationName: keyOf({
onMouseLeave: null
}),
dependencies: [ topLevelTypes.topMouseOut, topLevelTypes.topMouseOver ]
}
}, EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) return null;
if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) // Must not be a mouse in or mouse out - ignoring.
return null;
var win;
if (nativeEventTarget.window === nativeEventTarget) // `nativeEventTarget` is probably a window object.
win = nativeEventTarget; else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
win = doc ? doc.defaultView || doc.parentWindow : window;
}
var from, to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = targetInst;
var related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null;
} else from = null, to = targetInst;
if (from === to) // Nothing pertains to our managed components.
return null;
var fromNode = null == from ? win : ReactDOMComponentTree.getNodeFromInstance(from), toNode = null == to ? win : ReactDOMComponentTree.getNodeFromInstance(to), leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget);
leave.type = "mouseleave", leave.target = fromNode, leave.relatedTarget = toNode;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget);
return enter.type = "mouseenter", enter.target = toNode, enter.relatedTarget = fromNode,
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to), [ leave, enter ];
}
};
module.exports = EnterLeaveEventPlugin;
}, /* 60 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticMouseEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticUIEvent = __webpack_require__(61), ViewportMetrics = __webpack_require__(62), getEventModifierState = __webpack_require__(63), MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function(event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
return "which" in event ? button : 2 === button ? 2 : 4 === button ? 1 : 0;
},
buttons: null,
relatedTarget: function(event) {
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
},
// "Proprietary" Interface.
pageX: function(event) {
return "pageX" in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function(event) {
return "pageY" in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
}
};
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface), module.exports = SyntheticMouseEvent;
}, /* 61 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticUIEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticEvent = __webpack_require__(34), getEventTarget = __webpack_require__(55), UIEventInterface = {
view: function(event) {
if (event.view) return event.view;
var target = getEventTarget(event);
if (null != target && target.window === target) // target is a window object
return target;
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
return doc ? doc.defaultView || doc.parentWindow : window;
},
detail: function(event) {
return event.detail || 0;
}
};
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface), module.exports = SyntheticUIEvent;
}, /* 62 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ViewportMetrics
*/
"use strict";
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function(scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x, ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
}, /* 63 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventModifierState
*/
"use strict";
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
var syntheticEvent = this, nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) return nativeEvent.getModifierState(keyArg);
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : !1;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
Alt: "altKey",
Control: "ctrlKey",
Meta: "metaKey",
Shift: "shiftKey"
};
module.exports = getEventModifierState;
}, /* 64 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule HTMLDOMPropertyConfig
*/
"use strict";
var DOMProperty = __webpack_require__(39), MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY, HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE, HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS, HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE, HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE, HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE, HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(new RegExp("^(data|aria)-[" + DOMProperty.ATTRIBUTE_NAME_CHAR + "]*$")),
Properties: {
/**
* Standard Properties
*/
accept: 0,
acceptCharset: 0,
accessKey: 0,
action: 0,
allowFullScreen: HAS_BOOLEAN_VALUE,
allowTransparency: 0,
alt: 0,
async: HAS_BOOLEAN_VALUE,
autoComplete: 0,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: HAS_BOOLEAN_VALUE,
cellPadding: 0,
cellSpacing: 0,
charSet: 0,
challenge: 0,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
cite: 0,
classID: 0,
className: 0,
cols: HAS_POSITIVE_NUMERIC_VALUE,
colSpan: 0,
content: 0,
contentEditable: 0,
contextMenu: 0,
controls: HAS_BOOLEAN_VALUE,
coords: 0,
crossOrigin: 0,
data: 0,
// For `<object />` acts as `src`.
dateTime: 0,
"default": HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: 0,
disabled: HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: 0,
encType: 0,
form: 0,
formAction: 0,
formEncType: 0,
formMethod: 0,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: 0,
frameBorder: 0,
headers: 0,
height: 0,
hidden: HAS_BOOLEAN_VALUE,
high: 0,
href: 0,
hrefLang: 0,
htmlFor: 0,
httpEquiv: 0,
icon: 0,
id: 0,
inputMode: 0,
integrity: 0,
is: 0,
keyParams: 0,
keyType: 0,
kind: 0,
label: 0,
lang: 0,
list: 0,
loop: HAS_BOOLEAN_VALUE,
low: 0,
manifest: 0,
marginHeight: 0,
marginWidth: 0,
max: 0,
maxLength: 0,
media: 0,
mediaGroup: 0,
method: 0,
min: 0,
minLength: 0,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: 0,
nonce: 0,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: 0,
pattern: 0,
placeholder: 0,
poster: 0,
preload: 0,
profile: 0,
radioGroup: 0,
readOnly: HAS_BOOLEAN_VALUE,
rel: 0,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: 0,
rows: HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: HAS_NUMERIC_VALUE,
sandbox: 0,
scope: 0,
scoped: HAS_BOOLEAN_VALUE,
scrolling: 0,
seamless: HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: 0,
size: HAS_POSITIVE_NUMERIC_VALUE,
sizes: 0,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: 0,
src: 0,
srcDoc: 0,
srcLang: 0,
srcSet: 0,
start: HAS_NUMERIC_VALUE,
step: 0,
style: 0,
summary: 0,
tabIndex: 0,
target: 0,
title: 0,
// Setting .type throws on non-<input> tags
type: 0,
useMap: 0,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: 0,
wmode: 0,
wrap: 0,
/**
* RDFa Properties
*/
about: 0,
datatype: 0,
inlist: 0,
prefix: 0,
// property is also supported for OpenGraph in meta tags.
property: 0,
resource: 0,
"typeof": 0,
vocab: 0,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: 0,
autoCorrect: 0,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: 0,
// color is for Safari mask-icon link
color: 0,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: 0,
itemScope: HAS_BOOLEAN_VALUE,
itemType: 0,
// itemID and itemRef are for Microdata support as well but
// only specified in the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: 0,
itemRef: 0,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: 0,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: 0,
// IE-only attribute that controls focus behavior
unselectable: 0
},
DOMAttributeNames: {
acceptCharset: "accept-charset",
className: "class",
htmlFor: "for",
httpEquiv: "http-equiv"
},
DOMPropertyNames: {}
};
module.exports = HTMLDOMPropertyConfig;
}, /* 65 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentBrowserEnvironment
*/
"use strict";
var DOMChildrenOperations = __webpack_require__(66), ReactDOMIDOperations = __webpack_require__(78), ReactComponentBrowserEnvironment = {
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function(rootNodeID) {}
};
module.exports = ReactComponentBrowserEnvironment;
}, /* 66 */
/***/
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 DOMChildrenOperations
*/
"use strict";
function getNodeAfter(parentNode, node) {
// Special case for text components, which return [open, close] comments
// from getNativeNode.
return Array.isArray(node) && (node = node[1]), node ? node.nextSibling : parentNode.firstChild;
}
function insertLazyTreeChildAt(parentNode, childTree, referenceNode) {
DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode);
}
function moveChild(parentNode, childNode, referenceNode) {
Array.isArray(childNode) ? moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode) : insertChildAt(parentNode, childNode, referenceNode);
}
function removeChild(parentNode, childNode) {
if (Array.isArray(childNode)) {
var closingComment = childNode[1];
childNode = childNode[0], removeDelimitedText(parentNode, childNode, closingComment),
parentNode.removeChild(closingComment);
}
parentNode.removeChild(childNode);
}
function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) {
for (var node = openingComment; ;) {
var nextNode = node.nextSibling;
if (insertChildAt(parentNode, node, referenceNode), node === closingComment) break;
node = nextNode;
}
}
function removeDelimitedText(parentNode, startNode, closingComment) {
for (;;) {
var node = startNode.nextSibling;
if (node === closingComment) // The closing comment is removed by ReactMultiChild.
break;
parentNode.removeChild(node);
}
}
function replaceDelimitedText(openingComment, closingComment, stringText) {
var parentNode = openingComment.parentNode, nodeAfterComment = openingComment.nextSibling;
nodeAfterComment === closingComment ? // There are no text nodes between the opening and closing comments; insert
// a new one if stringText isn't empty.
stringText && insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment) : stringText ? (// Set the text content of the first node after the opening comment, and
// remove all following nodes up until the closing comment.
setTextContent(nodeAfterComment, stringText), removeDelimitedText(parentNode, nodeAfterComment, closingComment)) : removeDelimitedText(parentNode, openingComment, closingComment),
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, "replace text", stringText);
}
var DOMLazyTree = __webpack_require__(67), Danger = __webpack_require__(73), ReactMultiChildUpdateTypes = __webpack_require__(77), ReactDOMComponentTree = __webpack_require__(38), ReactInstrumentation = __webpack_require__(44), createMicrosoftUnsafeLocalFunction = __webpack_require__(69), setInnerHTML = __webpack_require__(72), setTextContent = __webpack_require__(70), insertChildAt = createMicrosoftUnsafeLocalFunction(function(parentNode, childNode, referenceNode) {
// We rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. (Using `undefined` is not allowed by all browsers so
// we are careful to use `null`.)
parentNode.insertBefore(childNode, referenceNode);
}), dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup;
"production" !== process.env.NODE_ENV && (dangerouslyReplaceNodeWithMarkup = function(oldChild, markup, prevInstance) {
if (Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup), 0 !== prevInstance._debugID) ReactInstrumentation.debugTool.onNativeOperation(prevInstance._debugID, "replace with", markup.toString()); else {
var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node);
0 !== nextInstance._debugID && ReactInstrumentation.debugTool.onNativeOperation(nextInstance._debugID, "mount", markup.toString());
}
});
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup,
replaceDelimitedText: replaceDelimitedText,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
processUpdates: function(parentNode, updates) {
if ("production" !== process.env.NODE_ENV) var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID;
for (var k = 0; k < updates.length; k++) {
var update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)),
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "insert child", {
toIndex: update.toIndex,
content: update.content.toString()
});
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)),
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "move child", {
fromIndex: update.fromIndex,
toIndex: update.toIndex
});
break;
case ReactMultiChildUpdateTypes.SET_MARKUP:
setInnerHTML(parentNode, update.content), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "replace children", update.content.toString());
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(parentNode, update.content), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "replace text", update.content.toString());
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
removeChild(parentNode, update.fromNode), "production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(parentNodeDebugID, "remove child", {
fromIndex: update.fromIndex
});
}
}
}
};
module.exports = DOMChildrenOperations;
}).call(exports, __webpack_require__(17));
}, /* 67 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMLazyTree
*/
"use strict";
function insertTreeChildren(tree) {
if (enableLazy) {
var node = tree.node, children = tree.children;
if (children.length) for (var i = 0; i < children.length; i++) insertTreeBefore(node, children[i], null); else null != tree.html ? node.innerHTML = tree.html : null != tree.text && setTextContent(node, tree.text);
}
}
function replaceChildWithTree(oldNode, newTree) {
oldNode.parentNode.replaceChild(newTree.node, oldNode), insertTreeChildren(newTree);
}
function queueChild(parentTree, childTree) {
enableLazy ? parentTree.children.push(childTree) : parentTree.node.appendChild(childTree.node);
}
function queueHTML(tree, html) {
enableLazy ? tree.html = html : tree.node.innerHTML = html;
}
function queueText(tree, text) {
enableLazy ? tree.text = text : setTextContent(tree.node, text);
}
function toString() {
return this.node.nodeName;
}
function DOMLazyTree(node) {
return {
node: node,
children: [],
html: null,
text: null,
toString: toString
};
}
var DOMNamespaces = __webpack_require__(68), createMicrosoftUnsafeLocalFunction = __webpack_require__(69), setTextContent = __webpack_require__(70), ELEMENT_NODE_TYPE = 1, DOCUMENT_FRAGMENT_NODE_TYPE = 11, enableLazy = "undefined" != typeof document && "number" == typeof document.documentMode || "undefined" != typeof navigator && "string" == typeof navigator.userAgent && /\bEdge\/\d/.test(navigator.userAgent), insertTreeBefore = createMicrosoftUnsafeLocalFunction(function(parentNode, tree, referenceNode) {
// DocumentFragments aren't actually part of the DOM after insertion so
// appending children won't update the DOM. We need to ensure the fragment
// is properly populated first, breaking out of our lazy approach for just
// this level. Also, some <object> plugins (like Flash Player) will read
// <param> nodes immediately upon insertion into the DOM, so <object>
// must also be populated prior to insertion into the DOM.
tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && "object" === tree.node.nodeName.toLowerCase() && (null == tree.node.namespaceURI || tree.node.namespaceURI === DOMNamespaces.html) ? (insertTreeChildren(tree),
parentNode.insertBefore(tree.node, referenceNode)) : (parentNode.insertBefore(tree.node, referenceNode),
insertTreeChildren(tree));
});
DOMLazyTree.insertTreeBefore = insertTreeBefore, DOMLazyTree.replaceChildWithTree = replaceChildWithTree,
DOMLazyTree.queueChild = queueChild, DOMLazyTree.queueHTML = queueHTML, DOMLazyTree.queueText = queueText,
module.exports = DOMLazyTree;
}, /* 68 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMNamespaces
*/
"use strict";
var DOMNamespaces = {
html: "http://www.w3.org/1999/xhtml",
mathml: "http://www.w3.org/1998/Math/MathML",
svg: "http://www.w3.org/2000/svg"
};
module.exports = DOMNamespaces;
}, /* 69 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createMicrosoftUnsafeLocalFunction
*/
/* globals MSApp */
"use strict";
/**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/
var createMicrosoftUnsafeLocalFunction = function(func) {
return "undefined" != typeof MSApp && MSApp.execUnsafeLocalFunction ? function(arg0, arg1, arg2, arg3) {
MSApp.execUnsafeLocalFunction(function() {
return func(arg0, arg1, arg2, arg3);
});
} : func;
};
module.exports = createMicrosoftUnsafeLocalFunction;
}, /* 70 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setTextContent
*/
"use strict";
var ExecutionEnvironment = __webpack_require__(28), escapeTextContentForBrowser = __webpack_require__(71), setInnerHTML = __webpack_require__(72), setTextContent = function(node, text) {
node.textContent = text;
};
ExecutionEnvironment.canUseDOM && ("textContent" in document.documentElement || (setTextContent = function(node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
})), module.exports = setTextContent;
}, /* 71 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule escapeTextContentForBrowser
*/
"use strict";
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
return ("" + text).replace(ESCAPE_REGEX, escaper);
}
var ESCAPE_LOOKUP = {
"&": "&",
">": ">",
"<": "<",
'"': """,
"'": "'"
}, ESCAPE_REGEX = /[&><"']/g;
module.exports = escapeTextContentForBrowser;
}, /* 72 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setInnerHTML
*/
"use strict";
var ExecutionEnvironment = __webpack_require__(28), WHITESPACE_TEST = /^[ \r\n\t\f]/, NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/, createMicrosoftUnsafeLocalFunction = __webpack_require__(69), setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node, html) {
node.innerHTML = html;
});
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement("div");
testElement.innerHTML = " ", "" === testElement.innerHTML && (setInnerHTML = function(node, html) {
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
node.parentNode && node.parentNode.replaceChild(node, node), WHITESPACE_TEST.test(html) || "<" === html[0] && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
// in hopes that this is preserved even if "\uFEFF" is transformed to
// the actual Unicode character (by Babel, for example).
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
node.innerHTML = String.fromCharCode(65279) + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
1 === textNode.data.length ? node.removeChild(textNode) : textNode.deleteData(0, 1);
} else node.innerHTML = html;
}), testElement = null;
}
module.exports = setInnerHTML;
}, /* 73 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Danger
*/
"use strict";
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(" "));
}
var DOMLazyTree = __webpack_require__(67), ExecutionEnvironment = __webpack_require__(28), createNodesFromMarkup = __webpack_require__(74), emptyFunction = __webpack_require__(25), getMarkupWrap = __webpack_require__(76), invariant = __webpack_require__(18), OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/, RESULT_INDEX_ATTR = "data-danger-index", Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function(markupList) {
ExecutionEnvironment.canUseDOM ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString for server rendering.") : invariant(!1);
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var nodeName, markupByNodeName = {}, i = 0; i < markupList.length; i++) markupList[i] ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyRenderMarkup(...): Missing markup.") : invariant(!1),
nodeName = getNodeName(markupList[i]), nodeName = getMarkupWrap(nodeName) ? nodeName : "*",
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [], markupByNodeName[nodeName][i] = markupList[i];
var resultList = [], resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) if (markupByNodeName.hasOwnProperty(nodeName)) {
var resultIndex, markupListByNodeName = markupByNodeName[nodeName];
for (resultIndex in markupListByNodeName) if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, // This index will be parsed back out below.
"$1 " + RESULT_INDEX_ATTR + '="' + resultIndex + '" ');
}
for (var renderNodes = createNodesFromMarkup(markupListByNodeName.join(""), emptyFunction), j = 0; j < renderNodes.length; ++j) {
var renderNode = renderNodes[j];
renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR) ? (resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR),
renderNode.removeAttribute(RESULT_INDEX_ATTR), resultList.hasOwnProperty(resultIndex) ? "production" !== process.env.NODE_ENV ? invariant(!1, "Danger: Assigning to an already-occupied result index.") : invariant(!1) : void 0,
resultList[resultIndex] = renderNode, resultListAssignmentCount += 1) : "production" !== process.env.NODE_ENV && console.error("Danger: Discarding unexpected node:", renderNode);
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
return resultListAssignmentCount !== resultList.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Danger: Did not assign to every index of resultList.") : invariant(!1) : void 0,
resultList.length !== markupList.length ? "production" !== process.env.NODE_ENV ? invariant(!1, "Danger: Expected markup to render %s nodes, but rendered %s.", markupList.length, resultList.length) : invariant(!1) : void 0,
resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) {
if (ExecutionEnvironment.canUseDOM ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.") : invariant(!1),
markup ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyReplaceNodeWithMarkup(...): Missing markup.") : invariant(!1),
"HTML" === oldChild.nodeName ? "production" !== process.env.NODE_ENV ? invariant(!1, "dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().") : invariant(!1) : void 0,
"string" == typeof markup) {
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
} else DOMLazyTree.replaceChildWithTree(oldChild, markup);
}
};
module.exports = Danger;
}).call(exports, __webpack_require__(17));
}, /* 74 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
"use strict";
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
dummyNode ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "createNodesFromMarkup dummy not initialized") : invariant(!1);
var nodeName = getNodeName(markup), wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
for (var wrapDepth = wrap[0]; wrapDepth--; ) node = node.lastChild;
} else node.innerHTML = markup;
var scripts = node.getElementsByTagName("script");
scripts.length && (handleScript ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "createNodesFromMarkup(...): Unexpected <script> element rendered.") : invariant(!1),
createArrayFromMixed(scripts).forEach(handleScript));
for (var nodes = Array.from(node.childNodes); node.lastChild; ) node.removeChild(node.lastChild);
return nodes;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
var ExecutionEnvironment = __webpack_require__(28), createArrayFromMixed = __webpack_require__(75), getMarkupWrap = __webpack_require__(76), invariant = __webpack_require__(18), dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement("div") : null, nodeNamePattern = /^\s*<(\w+)/;
module.exports = createNodesFromMarkup;
}).call(exports, __webpack_require__(17));
}, /* 75 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
"use strict";
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (Array.isArray(obj) || "object" != typeof obj && "function" != typeof obj ? "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Array-like object expected") : invariant(!1) : void 0,
"number" != typeof length ? "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Object needs a length property") : invariant(!1) : void 0,
0 === length || length - 1 in obj ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Object should have keys for indices") : invariant(!1),
"function" == typeof obj.callee ? "production" !== process.env.NODE_ENV ? invariant(!1, "toArray: Object can't be `arguments`. Use rest params (function(...args) {}) or Array.from() instead.") : invariant(!1) : void 0,
obj.hasOwnProperty) try {
return Array.prototype.slice.call(obj);
} catch (e) {}
for (var ret = Array(length), ii = 0; length > ii; ii++) ret[ii] = obj[ii];
return ret;
}
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
// not null/false
// arrays are objects, NodeLists are functions in Safari
// quacks like an array
// not window
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
// a real array
// arguments
// HTMLCollection/NodeList
return !!obj && ("object" == typeof obj || "function" == typeof obj) && "length" in obj && !("setInterval" in obj) && "number" != typeof obj.nodeType && (Array.isArray(obj) || "callee" in obj || "item" in obj);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
return hasArrayNature(obj) ? Array.isArray(obj) ? obj.slice() : toArray(obj) : [ obj ];
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var invariant = __webpack_require__(18);
module.exports = createArrayFromMixed;
}).call(exports, __webpack_require__(17));
}, /* 76 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
"use strict";
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
return dummyNode ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Markup wrapping node not initialized") : invariant(!1),
markupWrap.hasOwnProperty(nodeName) || (nodeName = "*"), shouldWrap.hasOwnProperty(nodeName) || ("*" === nodeName ? dummyNode.innerHTML = "<link />" : dummyNode.innerHTML = "<" + nodeName + "></" + nodeName + ">",
shouldWrap[nodeName] = !dummyNode.firstChild), shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*eslint-disable fb-www/unsafe-html */
var ExecutionEnvironment = __webpack_require__(28), invariant = __webpack_require__(18), dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement("div") : null, shouldWrap = {}, selectWrap = [ 1, '<select multiple="true">', "</select>" ], tableWrap = [ 1, "<table>", "</table>" ], trWrap = [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], svgWrap = [ 1, '<svg xmlns="http://www.w3.org/2000/svg">', "</svg>" ], markupWrap = {
"*": [ 1, "?<div>", "</div>" ],
area: [ 1, "<map>", "</map>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
param: [ 1, "<object>", "</object>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
optgroup: selectWrap,
option: selectWrap,
caption: tableWrap,
colgroup: tableWrap,
tbody: tableWrap,
tfoot: tableWrap,
thead: tableWrap,
td: trWrap,
th: trWrap
}, svgElements = [ "circle", "clipPath", "defs", "ellipse", "g", "image", "line", "linearGradient", "mask", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "stop", "text", "tspan" ];
svgElements.forEach(function(nodeName) {
markupWrap[nodeName] = svgWrap, shouldWrap[nodeName] = !0;
}), module.exports = getMarkupWrap;
}).call(exports, __webpack_require__(17));
}, /* 77 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChildUpdateTypes
*/
"use strict";
var keyMirror = __webpack_require__(16), ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
SET_MARKUP: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
}, /* 78 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMIDOperations
*/
"use strict";
var DOMChildrenOperations = __webpack_require__(66), ReactDOMComponentTree = __webpack_require__(38), ReactDOMIDOperations = {
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
dangerouslyProcessChildrenUpdates: function(parentInst, updates) {
var node = ReactDOMComponentTree.getNodeFromInstance(parentInst);
DOMChildrenOperations.processUpdates(node, updates);
}
};
module.exports = ReactDOMIDOperations;
}, /* 79 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponent
*/
/* global hasOwnProperty:true */
"use strict";
function getDeclarationErrorAddendum(internalInstance) {
if (internalInstance) {
var owner = internalInstance._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) return " This DOM node was rendered by `" + name + "`.";
}
}
return "";
}
function friendlyStringify(obj) {
if ("object" == typeof obj) {
if (Array.isArray(obj)) return "[" + obj.map(friendlyStringify).join(", ") + "]";
var pairs = [];
for (var key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) {
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
pairs.push(keyEscaped + ": " + friendlyStringify(obj[key]));
}
return "{" + pairs.join(", ") + "}";
}
return "string" == typeof obj ? JSON.stringify(obj) : "function" == typeof obj ? "[function object]" : String(obj);
}
function checkAndWarnForMutatedStyle(style1, style2, component) {
if (null != style1 && null != style2 && !shallowEqual(style1, style2)) {
var ownerName, componentName = component._tag, owner = component._currentElement._owner;
owner && (ownerName = owner.getName());
var hash = ownerName + "|" + componentName;
styleMutationWarning.hasOwnProperty(hash) || (styleMutationWarning[hash] = !0, "production" !== process.env.NODE_ENV ? warning(!1, "`%s` was passed a style object that has previously been mutated. Mutating `style` is deprecated. Consider cloning it beforehand. Check the `render` %s. Previous style: %s. Mutated style: %s.", componentName, owner ? "of `" + ownerName + "`" : "using <" + componentName + ">", friendlyStringify(style1), friendlyStringify(style2)) : void 0);
}
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
props && (// Note the use of `==` which checks for null or undefined.
voidElementTags[component._tag] && (null != props.children || null != props.dangerouslySetInnerHTML ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s is a void element tag and must not have `children` or use `props.dangerouslySetInnerHTML`.%s", component._tag, component._currentElement._owner ? " Check the render method of " + component._currentElement._owner.getName() + "." : "") : invariant(!1) : void 0),
null != props.dangerouslySetInnerHTML && (null != props.children ? "production" !== process.env.NODE_ENV ? invariant(!1, "Can only set one of `children` or `props.dangerouslySetInnerHTML`.") : invariant(!1) : void 0,
"object" == typeof props.dangerouslySetInnerHTML && HTML in props.dangerouslySetInnerHTML ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.") : invariant(!1)),
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == props.innerHTML, "Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`.") : void 0,
"production" !== process.env.NODE_ENV ? warning(props.suppressContentEditableWarning || !props.contentEditable || null == props.children, "A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.") : void 0,
"production" !== process.env.NODE_ENV ? warning(null == props.onFocusIn && null == props.onFocusOut, "React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React.") : void 0),
null != props.style && "object" != typeof props.style ? "production" !== process.env.NODE_ENV ? invariant(!1, "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.%s", getDeclarationErrorAddendum(component)) : invariant(!1) : void 0);
}
function enqueuePutListener(inst, registrationName, listener, transaction) {
if (!(transaction instanceof ReactServerRenderingTransaction)) {
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning("onScroll" !== registrationName || isEventSupported("scroll", !0), "This browser doesn't support the `onScroll` event") : void 0);
var containerInfo = inst._nativeContainerInfo, isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE, doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument;
listenTo(registrationName, doc), transaction.getReactMountReady().enqueue(putListener, {
inst: inst,
registrationName: registrationName,
listener: listener
});
}
}
function putListener() {
var listenerToPut = this;
EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener);
}
function optionPostMount() {
var inst = this;
ReactDOMOption.postMountWrapper(inst);
}
function trapBubbledEventsLocal() {
var inst = this;
inst._rootNodeID ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Must be mounted to trap events") : invariant(!1);
var node = getNode(inst);
switch (node ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "trapBubbledEvent(...): Requires node to be rendered.") : invariant(!1),
inst._tag) {
case "iframe":
case "object":
inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, "load", node) ];
break;
case "video":
case "audio":
inst._wrapperState.listeners = [];
// Create listener for each media event
for (var event in mediaEvents) mediaEvents.hasOwnProperty(event) && inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node));
break;
case "img":
inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, "error", node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, "load", node) ];
break;
case "form":
inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, "reset", node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, "submit", node) ];
break;
case "input":
case "select":
case "textarea":
inst._wrapperState.listeners = [ ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, "invalid", node) ];
}
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
function validateDangerousTag(tag) {
hasOwnProperty.call(validatedTagCache, tag) || (VALID_TAG_REGEX.test(tag) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "Invalid tag: %s", tag) : invariant(!1),
validatedTagCache[tag] = !0);
}
function isCustomComponent(tagName, props) {
return tagName.indexOf("-") >= 0 || null != props.is;
}
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(element) {
var tag = element.type;
validateDangerousTag(tag), this._currentElement = element, this._tag = tag.toLowerCase(),
this._namespaceURI = null, this._renderedChildren = null, this._previousStyle = null,
this._previousStyleCopy = null, this._nativeNode = null, this._nativeParent = null,
this._rootNodeID = null, this._domID = null, this._nativeContainerInfo = null, this._wrapperState = null,
this._topLevelWrapper = null, this._flags = 0, "production" !== process.env.NODE_ENV && (this._ancestorInfo = null,
this._contentDebugID = null);
}
var _assign = __webpack_require__(30), AutoFocusUtils = __webpack_require__(80), CSSPropertyOperations = __webpack_require__(82), DOMLazyTree = __webpack_require__(67), DOMNamespaces = __webpack_require__(68), DOMProperty = __webpack_require__(39), DOMPropertyOperations = __webpack_require__(90), EventConstants = __webpack_require__(15), EventPluginHub = __webpack_require__(20), EventPluginRegistry = __webpack_require__(21), ReactBrowserEventEmitter = __webpack_require__(95), ReactComponentBrowserEnvironment = __webpack_require__(65), ReactDOMButton = __webpack_require__(98), ReactDOMComponentFlags = __webpack_require__(40), ReactDOMComponentTree = __webpack_require__(38), ReactDOMInput = __webpack_require__(100), ReactDOMOption = __webpack_require__(109), ReactDOMSelect = __webpack_require__(113), ReactDOMTextarea = __webpack_require__(114), ReactInstrumentation = __webpack_require__(44), ReactMultiChild = __webpack_require__(115), ReactServerRenderingTransaction = __webpack_require__(128), emptyFunction = __webpack_require__(25), escapeTextContentForBrowser = __webpack_require__(71), invariant = __webpack_require__(18), isEventSupported = __webpack_require__(56), keyOf = __webpack_require__(36), shallowEqual = __webpack_require__(129), validateDOMNesting = __webpack_require__(130), warning = __webpack_require__(24), Flags = ReactDOMComponentFlags, deleteListener = EventPluginHub.deleteListener, getNode = ReactDOMComponentTree.getNodeFromInstance, listenTo = ReactBrowserEventEmitter.listenTo, registrationNameModules = EventPluginRegistry.registrationNameModules, CONTENT_TYPES = {
string: !0,
number: !0
}, STYLE = keyOf({
style: null
}), HTML = keyOf({
__html: null
}), RESERVED_PROPS = {
children: null,
dangerouslySetInnerHTML: null,
suppressContentEditableWarning: null
}, DOC_FRAGMENT_TYPE = 11, styleMutationWarning = {}, setContentChildForInstrumentation = emptyFunction;
"production" !== process.env.NODE_ENV && (setContentChildForInstrumentation = function(contentToUse) {
var debugID = this._debugID, contentDebugID = debugID + "#text";
this._contentDebugID = contentDebugID, ReactInstrumentation.debugTool.onSetDisplayName(contentDebugID, "#text"),
ReactInstrumentation.debugTool.onSetText(contentDebugID, "" + contentToUse), ReactInstrumentation.debugTool.onMountComponent(contentDebugID),
ReactInstrumentation.debugTool.onSetChildren(debugID, [ contentDebugID ]);
});
// There are so many media events, it makes sense to just
// maintain a list rather than create a `trapBubbledEvent` for each
var mediaEvents = {
topAbort: "abort",
topCanPlay: "canplay",
topCanPlayThrough: "canplaythrough",
topDurationChange: "durationchange",
topEmptied: "emptied",
topEncrypted: "encrypted",
topEnded: "ended",
topError: "error",
topLoadedData: "loadeddata",
topLoadedMetadata: "loadedmetadata",
topLoadStart: "loadstart",
topPause: "pause",
topPlay: "play",
topPlaying: "playing",
topProgress: "progress",
topRateChange: "ratechange",
topSeeked: "seeked",
topSeeking: "seeking",
topStalled: "stalled",
topSuspend: "suspend",
topTimeUpdate: "timeupdate",
topVolumeChange: "volumechange",
topWaiting: "waiting"
}, omittedCloseTags = {
area: !0,
base: !0,
br: !0,
col: !0,
embed: !0,
hr: !0,
img: !0,
input: !0,
keygen: !0,
link: !0,
meta: !0,
param: !0,
source: !0,
track: !0,
wbr: !0
}, newlineEatingTags = {
listing: !0,
pre: !0,
textarea: !0
}, voidElementTags = _assign({
menuitem: !0
}, omittedCloseTags), VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, validatedTagCache = {}, hasOwnProperty = {}.hasOwnProperty, globalIdCounter = 1;
ReactDOMComponent.displayName = "ReactDOMComponent", ReactDOMComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?ReactDOMComponent} the containing DOM component instance
* @param {?object} info about the native container
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) {
this._rootNodeID = globalIdCounter++, this._domID = nativeContainerInfo._idCounter++,
this._nativeParent = nativeParent, this._nativeContainerInfo = nativeContainerInfo;
var props = this._currentElement.props;
switch (this._tag) {
case "iframe":
case "object":
case "img":
case "form":
case "video":
case "audio":
this._wrapperState = {
listeners: null
}, transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case "button":
props = ReactDOMButton.getNativeProps(this, props, nativeParent);
break;
case "input":
ReactDOMInput.mountWrapper(this, props, nativeParent), props = ReactDOMInput.getNativeProps(this, props),
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case "option":
ReactDOMOption.mountWrapper(this, props, nativeParent), props = ReactDOMOption.getNativeProps(this, props);
break;
case "select":
ReactDOMSelect.mountWrapper(this, props, nativeParent), props = ReactDOMSelect.getNativeProps(this, props),
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case "textarea":
ReactDOMTextarea.mountWrapper(this, props, nativeParent), props = ReactDOMTextarea.getNativeProps(this, props),
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
}
assertValidProps(this, props);
// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var namespaceURI, parentTag;
if (null != nativeParent ? (namespaceURI = nativeParent._namespaceURI, parentTag = nativeParent._tag) : nativeContainerInfo._tag && (namespaceURI = nativeContainerInfo._namespaceURI,
parentTag = nativeContainerInfo._tag), (null == namespaceURI || namespaceURI === DOMNamespaces.svg && "foreignobject" === parentTag) && (namespaceURI = DOMNamespaces.html),
namespaceURI === DOMNamespaces.html && ("svg" === this._tag ? namespaceURI = DOMNamespaces.svg : "math" === this._tag && (namespaceURI = DOMNamespaces.mathml)),
this._namespaceURI = namespaceURI, "production" !== process.env.NODE_ENV) {
var parentInfo;
null != nativeParent ? parentInfo = nativeParent._ancestorInfo : nativeContainerInfo._tag && (parentInfo = nativeContainerInfo._ancestorInfo),
parentInfo && // parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(this._tag, this, parentInfo), this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
}
var mountImage;
if (transaction.useCreateElement) {
var el, ownerDocument = nativeContainerInfo._ownerDocument;
if (namespaceURI === DOMNamespaces.html) if ("script" === this._tag) {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div = ownerDocument.createElement("div"), type = this._currentElement.type;
div.innerHTML = "<" + type + "></" + type + ">", el = div.removeChild(div.firstChild);
} else el = ownerDocument.createElement(this._currentElement.type, props.is || null); else el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type);
ReactDOMComponentTree.precacheNode(this, el), this._flags |= Flags.hasCachedChildNodes,
this._nativeParent || DOMPropertyOperations.setAttributeForRoot(el), this._updateDOMProperties(null, props, transaction);
var lazyTree = DOMLazyTree(el);
this._createInitialChildren(transaction, props, context, lazyTree), mountImage = lazyTree;
} else {
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props), tagContent = this._createContentMarkup(transaction, props, context);
mountImage = !tagContent && omittedCloseTags[this._tag] ? tagOpen + "/>" : tagOpen + ">" + tagContent + "</" + this._currentElement.type + ">";
}
switch (this._tag) {
case "button":
case "input":
case "select":
case "textarea":
props.autoFocus && transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
break;
case "option":
transaction.getReactMountReady().enqueue(optionPostMount, this);
}
return mountImage;
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function(transaction, props) {
var ret = "<" + this._currentElement.type;
for (var propKey in props) if (props.hasOwnProperty(propKey)) {
var propValue = props[propKey];
if (null != propValue) if (registrationNameModules.hasOwnProperty(propKey)) propValue && enqueuePutListener(this, propKey, propValue, transaction); else {
propKey === STYLE && (propValue && ("production" !== process.env.NODE_ENV && (// See `_updateDOMProperties`. style block
this._previousStyle = propValue), propValue = this._previousStyleCopy = _assign({}, props.style)),
propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this));
var markup = null;
null != this._tag && isCustomComponent(this._tag, props) ? RESERVED_PROPS.hasOwnProperty(propKey) || (markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue)) : markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue),
markup && (ret += " " + markup);
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
return transaction.renderToStaticMarkup ? ret : (this._nativeParent || (ret += " " + DOMPropertyOperations.createMarkupForRoot()),
ret += " " + DOMPropertyOperations.createMarkupForID(this._domID));
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function(transaction, props, context) {
var ret = "", innerHTML = props.dangerouslySetInnerHTML;
if (null != innerHTML) null != innerHTML.__html && (ret = innerHTML.__html); else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null, childrenToUse = null != contentToUse ? null : props.children;
if (null != contentToUse) ret = escapeTextContentForBrowser(contentToUse), "production" !== process.env.NODE_ENV && setContentChildForInstrumentation.call(this, contentToUse); else if (null != childrenToUse) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
ret = mountImages.join("");
}
}
return newlineEatingTags[this._tag] && "\n" === ret.charAt(0) ? "\n" + ret : ret;
},
_createInitialChildren: function(transaction, props, context, lazyTree) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (null != innerHTML) null != innerHTML.__html && DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null, childrenToUse = null != contentToUse ? null : props.children;
if (null != contentToUse) // TODO: Validate that text is allowed as a child of this node
"production" !== process.env.NODE_ENV && setContentChildForInstrumentation.call(this, contentToUse),
DOMLazyTree.queueText(lazyTree, contentToUse); else if (null != childrenToUse) for (var mountImages = this.mountChildren(childrenToUse, transaction, context), i = 0; i < mountImages.length; i++) DOMLazyTree.queueChild(lazyTree, mountImages[i]);
}
},
/**
* Receives a next element and updates the component.
*
* @internal
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
*/
receiveComponent: function(nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement, this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function(transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props, nextProps = this._currentElement.props;
switch (this._tag) {
case "button":
lastProps = ReactDOMButton.getNativeProps(this, lastProps), nextProps = ReactDOMButton.getNativeProps(this, nextProps);
break;
case "input":
ReactDOMInput.updateWrapper(this), lastProps = ReactDOMInput.getNativeProps(this, lastProps),
nextProps = ReactDOMInput.getNativeProps(this, nextProps);
break;
case "option":
lastProps = ReactDOMOption.getNativeProps(this, lastProps), nextProps = ReactDOMOption.getNativeProps(this, nextProps);
break;
case "select":
lastProps = ReactDOMSelect.getNativeProps(this, lastProps), nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
break;
case "textarea":
ReactDOMTextarea.updateWrapper(this), lastProps = ReactDOMTextarea.getNativeProps(this, lastProps),
nextProps = ReactDOMTextarea.getNativeProps(this, nextProps);
}
assertValidProps(this, nextProps), this._updateDOMProperties(lastProps, nextProps, transaction),
this._updateDOMChildren(lastProps, nextProps, transaction, context), "select" === this._tag && // <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {object} nextProps
* @param {?DOMElement} node
*/
_updateDOMProperties: function(lastProps, nextProps, transaction) {
var propKey, styleName, styleUpdates;
for (propKey in lastProps) if (!nextProps.hasOwnProperty(propKey) && lastProps.hasOwnProperty(propKey) && null != lastProps[propKey]) if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) lastStyle.hasOwnProperty(styleName) && (styleUpdates = styleUpdates || {},
styleUpdates[styleName] = "");
this._previousStyleCopy = null;
} else registrationNameModules.hasOwnProperty(propKey) ? lastProps[propKey] && // Only call deleteListener if there was a listener previously or
// else willDeleteListener gets called when there wasn't actually a
// listener (e.g., onClick={null})
deleteListener(this, propKey) : (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) && DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
for (propKey in nextProps) {
var nextProp = nextProps[propKey], lastProp = propKey === STYLE ? this._previousStyleCopy : null != lastProps ? lastProps[propKey] : void 0;
if (nextProps.hasOwnProperty(propKey) && nextProp !== lastProp && (null != nextProp || null != lastProp)) if (propKey === STYLE) if (nextProp ? ("production" !== process.env.NODE_ENV && (checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this),
this._previousStyle = nextProp), nextProp = this._previousStyleCopy = _assign({}, nextProp)) : this._previousStyleCopy = null,
lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) !lastProp.hasOwnProperty(styleName) || nextProp && nextProp.hasOwnProperty(styleName) || (styleUpdates = styleUpdates || {},
styleUpdates[styleName] = "");
// Update styles that changed since `lastProp`.
for (styleName in nextProp) nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName] && (styleUpdates = styleUpdates || {},
styleUpdates[styleName] = nextProp[styleName]);
} else // Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp; else if (registrationNameModules.hasOwnProperty(propKey)) nextProp ? enqueuePutListener(this, propKey, nextProp, transaction) : lastProp && deleteListener(this, propKey); else if (isCustomComponent(this._tag, nextProps)) RESERVED_PROPS.hasOwnProperty(propKey) || DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
var node = getNode(this);
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertently setting to a string. This
// brings us in line with the same behavior we have on initial render.
null != nextProp ? DOMPropertyOperations.setValueForProperty(node, propKey, nextProp) : DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
styleUpdates && CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this);
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {object} context
*/
_updateDOMChildren: function(lastProps, nextProps, transaction, context) {
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null, nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null, lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html, nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html, lastChildren = null != lastContent ? null : lastProps.children, nextChildren = null != nextContent ? null : nextProps.children, lastHasContentOrHtml = null != lastContent || null != lastHtml, nextHasContentOrHtml = null != nextContent || null != nextHtml;
null != lastChildren && null == nextChildren ? this.updateChildren(null, transaction, context) : lastHasContentOrHtml && !nextHasContentOrHtml && (this.updateTextContent(""),
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onSetChildren(this._debugID, [])),
null != nextContent ? lastContent !== nextContent && (this.updateTextContent("" + nextContent),
"production" !== process.env.NODE_ENV && (this._contentDebugID = this._debugID + "#text",
setContentChildForInstrumentation.call(this, nextContent))) : null != nextHtml ? (lastHtml !== nextHtml && this.updateMarkup("" + nextHtml),
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onSetChildren(this._debugID, [])) : null != nextChildren && ("production" !== process.env.NODE_ENV && this._contentDebugID && (ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID),
this._contentDebugID = null), this.updateChildren(nextChildren, transaction, context));
},
getNativeNode: function() {
return getNode(this);
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function(safely) {
switch (this._tag) {
case "iframe":
case "object":
case "img":
case "form":
case "video":
case "audio":
var listeners = this._wrapperState.listeners;
if (listeners) for (var i = 0; i < listeners.length; i++) listeners[i].remove();
break;
case "html":
case "head":
case "body":
"production" !== process.env.NODE_ENV ? invariant(!1, "<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.", this._tag) : invariant(!1);
}
this.unmountChildren(safely), ReactDOMComponentTree.uncacheNode(this), EventPluginHub.deleteAllListeners(this),
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID), this._rootNodeID = null,
this._domID = null, this._wrapperState = null, "production" !== process.env.NODE_ENV && this._contentDebugID && (ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID),
this._contentDebugID = null);
},
getPublicInstance: function() {
return getNode(this);
}
}, _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin),
module.exports = ReactDOMComponent;
}).call(exports, __webpack_require__(17));
}, /* 80 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AutoFocusUtils
*/
"use strict";
var ReactDOMComponentTree = __webpack_require__(38), focusNode = __webpack_require__(81), AutoFocusUtils = {
focusDOMComponent: function() {
focusNode(ReactDOMComponentTree.getNodeFromInstance(this));
}
};
module.exports = AutoFocusUtils;
}, /* 81 */
/***/
function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
"use strict";
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
}, /* 82 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSPropertyOperations
*/
"use strict";
var CSSProperty = __webpack_require__(83), ExecutionEnvironment = __webpack_require__(28), ReactInstrumentation = __webpack_require__(44), camelizeStyleName = __webpack_require__(84), dangerousStyleValue = __webpack_require__(86), hyphenateStyleName = __webpack_require__(87), memoizeStringOnly = __webpack_require__(89), warning = __webpack_require__(24), processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
}), hasShorthandPropertyBug = !1, styleFloatAccessor = "cssFloat";
if (ExecutionEnvironment.canUseDOM) {
var tempStyle = document.createElement("div").style;
try {
// IE8 throws "Invalid argument." if resetting shorthand style properties.
tempStyle.font = "";
} catch (e) {
hasShorthandPropertyBug = !0;
}
// IE8 only supports accessing cssFloat (standard) as styleFloat
void 0 === document.documentElement.style.cssFloat && (styleFloatAccessor = "styleFloat");
}
if ("production" !== process.env.NODE_ENV) // 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/, badStyleValueWithSemicolonPattern = /;\s*$/, warnedStyleNames = {}, warnedStyleValues = {}, warnedForNaNValue = !1, warnHyphenatedStyleName = function(name, owner) {
warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name] || (warnedStyleNames[name] = !0,
"production" !== process.env.NODE_ENV ? warning(!1, "Unsupported style property %s. Did you mean %s?%s", name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0);
}, warnBadVendoredStyleName = function(name, owner) {
warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name] || (warnedStyleNames[name] = !0,
"production" !== process.env.NODE_ENV ? warning(!1, "Unsupported vendor-prefixed style property %s. Did you mean %s?%s", name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0);
}, warnStyleValueWithSemicolon = function(name, value, owner) {
warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value] || (warnedStyleValues[value] = !0,
"production" !== process.env.NODE_ENV ? warning(!1, 'Style property values shouldn\'t contain a semicolon.%s Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, "")) : void 0);
}, warnStyleValueIsNaN = function(name, value, owner) {
warnedForNaNValue || (warnedForNaNValue = !0, "production" !== process.env.NODE_ENV ? warning(!1, "`NaN` is an invalid value for the `%s` css style property.%s", name, checkRenderMessage(owner)) : void 0);
}, checkRenderMessage = function(owner) {
if (owner) {
var name = owner.getName();
if (name) return " Check the render method of `" + name + "`.";
}
return "";
}, warnValidStyle = function(name, value, component) {
var owner;
component && (owner = component._currentElement._owner), name.indexOf("-") > -1 ? warnHyphenatedStyleName(name, owner) : badVendoredStyleNamePattern.test(name) ? warnBadVendoredStyleName(name, owner) : badStyleValueWithSemicolonPattern.test(value) && warnStyleValueWithSemicolon(name, value, owner),
"number" == typeof value && isNaN(value) && warnStyleValueIsNaN(name, value, owner);
};
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @param {ReactDOMComponent} component
* @return {?string}
*/
createMarkupForStyles: function(styles, component) {
var serialized = "";
for (var styleName in styles) if (styles.hasOwnProperty(styleName)) {
var styleValue = styles[styleName];
"production" !== process.env.NODE_ENV && warnValidStyle(styleName, styleValue, component),
null != styleValue && (serialized += processStyleName(styleName) + ":", serialized += dangerousStyleValue(styleName, styleValue, component) + ";");
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
* @param {ReactDOMComponent} component
*/
setValueForStyles: function(node, styles, component) {
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onNativeOperation(component._debugID, "update styles", styles);
var style = node.style;
for (var styleName in styles) if (styles.hasOwnProperty(styleName)) {
"production" !== process.env.NODE_ENV && warnValidStyle(styleName, styles[styleName], component);
var styleValue = dangerousStyleValue(styleName, styles[styleName], component);
if ("float" !== styleName && "cssFloat" !== styleName || (styleName = styleFloatAccessor),
styleValue) style[styleName] = styleValue; else {
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) // Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) style[individualStyleName] = ""; else style[styleName] = "";
}
}
}
};
module.exports = CSSPropertyOperations;
}).call(exports, __webpack_require__(17));
}, /* 83 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSProperty
*/
"use strict";
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: !0,
borderImageOutset: !0,
borderImageSlice: !0,
borderImageWidth: !0,
boxFlex: !0,
boxFlexGroup: !0,
boxOrdinalGroup: !0,
columnCount: !0,
flex: !0,
flexGrow: !0,
flexPositive: !0,
flexShrink: !0,
flexNegative: !0,
flexOrder: !0,
gridRow: !0,
gridColumn: !0,
fontWeight: !0,
lineClamp: !0,
lineHeight: !0,
opacity: !0,
order: !0,
orphans: !0,
tabSize: !0,
widows: !0,
zIndex: !0,
zoom: !0,
// SVG-related properties
fillOpacity: !0,
floodOpacity: !0,
stopOpacity: !0,
strokeDasharray: !0,
strokeDashoffset: !0,
strokeMiterlimit: !0,
strokeOpacity: !0,
strokeWidth: !0
}, prefixes = [ "Webkit", "ms", "Moz", "O" ];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function(prop) {
prefixes.forEach(function(prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: !0,
backgroundColor: !0,
backgroundImage: !0,
backgroundPositionX: !0,
backgroundPositionY: !0,
backgroundRepeat: !0
},
backgroundPosition: {
backgroundPositionX: !0,
backgroundPositionY: !0
},
border: {
borderWidth: !0,
borderStyle: !0,
borderColor: !0
},
borderBottom: {
borderBottomWidth: !0,
borderBottomStyle: !0,
borderBottomColor: !0
},
borderLeft: {
borderLeftWidth: !0,
borderLeftStyle: !0,
borderLeftColor: !0
},
borderRight: {
borderRightWidth: !0,
borderRightStyle: !0,
borderRightColor: !0
},
borderTop: {
borderTopWidth: !0,
borderTopStyle: !0,
borderTopColor: !0
},
font: {
fontStyle: !0,
fontVariant: !0,
fontWeight: !0,
fontSize: !0,
lineHeight: !0,
fontFamily: !0
},
outline: {
outlineWidth: !0,
outlineStyle: !0,
outlineColor: !0
}
}, CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
}, /* 84 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
"use strict";
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, "ms-"));
}
var camelize = __webpack_require__(85), msPattern = /^-ms-/;
module.exports = camelizeStyleName;
}, /* 85 */
/***/
function(module, exports) {
"use strict";
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function(_, character) {
return character.toUpperCase();
});
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _hyphenPattern = /-(.)/g;
module.exports = camelize;
}, /* 86 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule dangerousStyleValue
*/
"use strict";
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = null == value || "boolean" == typeof value || "" === value;
if (isEmpty) return "";
var isNonNumeric = isNaN(value);
if (isNonNumeric || 0 === value || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) return "" + value;
if ("string" == typeof value) {
if ("production" !== process.env.NODE_ENV && component) {
var owner = component._currentElement._owner, ownerName = owner ? owner.getName() : null;
ownerName && !styleWarnings[ownerName] && (styleWarnings[ownerName] = {});
var warned = !1;
if (ownerName) {
var warnings = styleWarnings[ownerName];
warned = warnings[name], warned || (warnings[name] = !0);
}
warned || ("production" !== process.env.NODE_ENV ? warning(!1, "a `%s` tag (owner: `%s`) was passed a numeric string value for CSS property `%s` (value: `%s`) which will be treated as a unitless number in a future version of React.", component._currentElement.type, ownerName || "unknown", name, value) : void 0);
}
value = value.trim();
}
return value + "px";
}
var CSSProperty = __webpack_require__(83), warning = __webpack_require__(24), isUnitlessNumber = CSSProperty.isUnitlessNumber, styleWarnings = {};
module.exports = dangerousStyleValue;
}).call(exports, __webpack_require__(17));
}, /* 87 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
"use strict";
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, "-ms-");
}
var hyphenate = __webpack_require__(88), msPattern = /^ms-/;
module.exports = hyphenateStyleName;
}, /* 88 */
/***/
function(module, exports) {
"use strict";
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, "-$1").toLowerCase();
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
module.exports = hyphenate;
}, /* 89 */
/***/
function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @typechecks static-only
*/
"use strict";
/**
* Memoizes the return value of a function that accepts one string argument.
*/
function memoizeStringOnly(callback) {
var cache = {};
return function(string) {
return cache.hasOwnProperty(string) || (cache[string] = callback.call(this, string)),
cache[string];
};
}
module.exports = memoizeStringOnly;
}, /* 90 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMPropertyOperations
*/
"use strict";
function isAttributeNameSafe(attributeName) {
return validatedAttributeNameCache.hasOwnProperty(attributeName) ? !0 : illegalAttributeNameCache.hasOwnProperty(attributeName) ? !1 : VALID_ATTRIBUTE_NAME_REGEX.test(attributeName) ? (validatedAttributeNameCache[attributeName] = !0,
!0) : (illegalAttributeNameCache[attributeName] = !0, "production" !== process.env.NODE_ENV ? warning(!1, "Invalid attribute name: `%s`", attributeName) : void 0,
!1);
}
function shouldIgnoreValue(propertyInfo, value) {
return null == value || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && 1 > value || propertyInfo.hasOverloadedBooleanValue && value === !1;
}
var DOMProperty = __webpack_require__(39), ReactDOMComponentTree = __webpack_require__(38), ReactDOMInstrumentation = __webpack_require__(91), ReactInstrumentation = __webpack_require__(44), quoteAttributeValueForBrowser = __webpack_require__(94), warning = __webpack_require__(24), VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + DOMProperty.ATTRIBUTE_NAME_START_CHAR + "][" + DOMProperty.ATTRIBUTE_NAME_CHAR + "]*$"), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}, DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function(id) {
return DOMProperty.ID_ATTRIBUTE_NAME + "=" + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function(node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
createMarkupForRoot: function() {
return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""';
},
setAttributeForRoot: function(node) {
node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, "");
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function(name, value) {
"production" !== process.env.NODE_ENV && ReactDOMInstrumentation.debugTool.onCreateMarkupForProperty(name, value);
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) return "";
var attributeName = propertyInfo.attributeName;
return propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === !0 ? attributeName + '=""' : attributeName + "=" + quoteAttributeValueForBrowser(value);
}
return DOMProperty.isCustomAttribute(name) ? null == value ? "" : name + "=" + quoteAttributeValueForBrowser(value) : null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function(name, value) {
return isAttributeNameSafe(name) && null != value ? name + "=" + quoteAttributeValueForBrowser(value) : "";
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function(node, name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) mutationMethod(node, value); else {
if (shouldIgnoreValue(propertyInfo, value)) return void this.deleteValueForProperty(node, name);
if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
// property type before comparing; only `value` does and is string.
propertyInfo.hasSideEffects && "" + node[propName] == "" + value || (// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propName] = value);
} else {
var attributeName = propertyInfo.attributeName, namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
namespace ? node.setAttributeNS(namespace, attributeName, "" + value) : propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === !0 ? node.setAttribute(attributeName, "") : node.setAttribute(attributeName, "" + value);
}
}
} else if (DOMProperty.isCustomAttribute(name)) return void DOMPropertyOperations.setValueForAttribute(node, name, value);
if ("production" !== process.env.NODE_ENV) {
ReactDOMInstrumentation.debugTool.onSetValueForProperty(node, name, value);
var payload = {};
payload[name] = value, ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, "update attribute", payload);
}
},
setValueForAttribute: function(node, name, value) {
if (isAttributeNameSafe(name) && (null == value ? node.removeAttribute(name) : node.setAttribute(name, "" + value),
"production" !== process.env.NODE_ENV)) {
var payload = {};
payload[name] = value, ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, "update attribute", payload);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function(node, name) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) mutationMethod(node, void 0); else if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
propertyInfo.hasBooleanValue ? // No HAS_SIDE_EFFECTS logic here, only `value` has it and is string.
node[propName] = !1 : propertyInfo.hasSideEffects && "" + node[propName] == "" || (node[propName] = "");
} else node.removeAttribute(propertyInfo.attributeName);
} else DOMProperty.isCustomAttribute(name) && node.removeAttribute(name);
"production" !== process.env.NODE_ENV && (ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name),
ReactInstrumentation.debugTool.onNativeOperation(ReactDOMComponentTree.getInstanceFromNode(node)._debugID, "remove attribute", name));
}
};
module.exports = DOMPropertyOperations;
}).call(exports, __webpack_require__(17));
}, /* 91 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMInstrumentation
*/
"use strict";
var ReactDOMDebugTool = __webpack_require__(92);
module.exports = {
debugTool: ReactDOMDebugTool
};
}, /* 92 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMDebugTool
*/
"use strict";
function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
"production" !== process.env.NODE_ENV && eventHandlers.forEach(function(handler) {
try {
handler[handlerFunctionName] && handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5);
} catch (e) {
"production" !== process.env.NODE_ENV ? warning(!handlerDoesThrowForEvent[handlerFunctionName], "exception thrown by devtool while handling %s: %s", handlerFunctionName, e.message) : void 0,
handlerDoesThrowForEvent[handlerFunctionName] = !0;
}
});
}
var ReactDOMUnknownPropertyDevtool = __webpack_require__(93), warning = __webpack_require__(24), eventHandlers = [], handlerDoesThrowForEvent = {}, ReactDOMDebugTool = {
addDevtool: function(devtool) {
eventHandlers.push(devtool);
},
removeDevtool: function(devtool) {
for (var i = 0; i < eventHandlers.length; i++) eventHandlers[i] === devtool && (eventHandlers.splice(i, 1),
i--);
},
onCreateMarkupForProperty: function(name, value) {
emitEvent("onCreateMarkupForProperty", name, value);
},
onSetValueForProperty: function(node, name, value) {
emitEvent("onSetValueForProperty", node, name, value);
},
onDeleteValueForProperty: function(node, name) {
emitEvent("onDeleteValueForProperty", node, name);
}
};
ReactDOMDebugTool.addDevtool(ReactDOMUnknownPropertyDevtool), module.exports = ReactDOMDebugTool;
}).call(exports, __webpack_require__(17));
}, /* 93 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMUnknownPropertyDevtool
*/
"use strict";
var DOMProperty = __webpack_require__(39), EventPluginRegistry = __webpack_require__(21), warning = __webpack_require__(24);
if ("production" !== process.env.NODE_ENV) var reactProps = {
children: !0,
dangerouslySetInnerHTML: !0,
key: !0,
ref: !0
}, warnedProperties = {}, warnUnknownProperty = function(name) {
if (!DOMProperty.properties.hasOwnProperty(name) && !DOMProperty.isCustomAttribute(name) && !(reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name])) {
warnedProperties[name] = !0;
var lowerCasedName = name.toLowerCase(), standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
"production" !== process.env.NODE_ENV ? warning(null == standardName, "Unknown DOM property %s. Did you mean %s?", name, standardName) : void 0;
var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null;
"production" !== process.env.NODE_ENV ? warning(null == registrationName, "Unknown event handler property %s. Did you mean `%s`?", name, registrationName) : void 0;
}
};
var ReactDOMUnknownPropertyDevtool = {
onCreateMarkupForProperty: function(name, value) {
warnUnknownProperty(name);
},
onSetValueForProperty: function(node, name, value) {
warnUnknownProperty(name);
},
onDeleteValueForProperty: function(node, name) {
warnUnknownProperty(name);
}
};
module.exports = ReactDOMUnknownPropertyDevtool;
}).call(exports, __webpack_require__(17));
}, /* 94 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule quoteAttributeValueForBrowser
*/
"use strict";
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
var escapeTextContentForBrowser = __webpack_require__(71);
module.exports = quoteAttributeValueForBrowser;
}, /* 95 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactBrowserEventEmitter
*/
"use strict";
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
return Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey) || (mountAt[topListenersIDKey] = reactTopListenersCounter++,
alreadyListeningTo[mountAt[topListenersIDKey]] = {}), alreadyListeningTo[mountAt[topListenersIDKey]];
}
var hasEventPageXY, _assign = __webpack_require__(30), EventConstants = __webpack_require__(15), EventPluginRegistry = __webpack_require__(21), ReactEventEmitterMixin = __webpack_require__(96), ViewportMetrics = __webpack_require__(62), getVendorPrefixedEventName = __webpack_require__(97), isEventSupported = __webpack_require__(56), alreadyListeningTo = {}, isMonitoringScrollValue = !1, reactTopListenersCounter = 0, topEventMapping = {
topAbort: "abort",
topAnimationEnd: getVendorPrefixedEventName("animationend") || "animationend",
topAnimationIteration: getVendorPrefixedEventName("animationiteration") || "animationiteration",
topAnimationStart: getVendorPrefixedEventName("animationstart") || "animationstart",
topBlur: "blur",
topCanPlay: "canplay",
topCanPlayThrough: "canplaythrough",
topChange: "change",
topClick: "click",
topCompositionEnd: "compositionend",
topCompositionStart: "compositionstart",
topCompositionUpdate: "compositionupdate",
topContextMenu: "contextmenu",
topCopy: "copy",
topCut: "cut",
topDoubleClick: "dblclick",
topDrag: "drag",
topDragEnd: "dragend",
topDragEnter: "dragenter",
topDragExit: "dragexit",
topDragLeave: "dragleave",
topDragOver: "dragover",
topDragStart: "dragstart",
topDrop: "drop",
topDurationChange: "durationchange",
topEmptied: "emptied",
topEncrypted: "encrypted",
topEnded: "ended",
topError: "error",
topFocus: "focus",
topInput: "input",
topKeyDown: "keydown",
topKeyPress: "keypress",
topKeyUp: "keyup",
topLoadedData: "loadeddata",
topLoadedMetadata: "loadedmetadata",
topLoadStart: "loadstart",
topMouseDown: "mousedown",
topMouseMove: "mousemove",
topMouseOut: "mouseout",
topMouseOver: "mouseover",
topMouseUp: "mouseup",
topPaste: "paste",
topPause: "pause",
topPlay: "play",
topPlaying: "playing",
topProgress: "progress",
topRateChange: "ratechange",
topScroll: "scroll",
topSeeked: "seeked",
topSeeking: "seeking",
topSelectionChange: "selectionchange",
topStalled: "stalled",
topSuspend: "suspend",
topTextInput: "textInput",
topTimeUpdate: "timeupdate",
topTouchCancel: "touchcancel",
topTouchEnd: "touchend",
topTouchMove: "touchmove",
topTouchStart: "touchstart",
topTransitionEnd: getVendorPrefixedEventName("transitionend") || "transitionend",
topVolumeChange: "volumechange",
topWaiting: "waiting",
topWheel: "wheel"
}, topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2), ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function(ReactEventListener) {
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel), ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function(enabled) {
ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function() {
return !(!ReactBrowserEventEmitter.ReactEventListener || !ReactBrowserEventEmitter.ReactEventListener.isEnabled());
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function(registrationName, contentDocumentHandle) {
for (var mountAt = contentDocumentHandle, isListening = getListeningForDocument(mountAt), dependencies = EventPluginRegistry.registrationNameDependencies[registrationName], topLevelTypes = EventConstants.topLevelTypes, i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
isListening.hasOwnProperty(dependency) && isListening[dependency] || (dependency === topLevelTypes.topWheel ? isEventSupported("wheel") ? ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, "wheel", mountAt) : isEventSupported("mousewheel") ? ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, "mousewheel", mountAt) : ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, "DOMMouseScroll", mountAt) : dependency === topLevelTypes.topScroll ? isEventSupported("scroll", !0) ? ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, "scroll", mountAt) : ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, "scroll", ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE) : dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur ? (isEventSupported("focus", !0) ? (ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, "focus", mountAt),
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, "blur", mountAt)) : isEventSupported("focusin") && (ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, "focusin", mountAt),
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, "focusout", mountAt)),
isListening[topLevelTypes.topBlur] = !0, isListening[topLevelTypes.topFocus] = !0) : topEventMapping.hasOwnProperty(dependency) && ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt),
isListening[dependency] = !0);
}
},
trapBubbledEvent: function(topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
},
trapCapturedEvent: function(topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when
* pageX/pageY isn't supported (legacy browsers).
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function() {
if (void 0 === hasEventPageXY && (hasEventPageXY = document.createEvent && "pageX" in document.createEvent("MouseEvent")),
!hasEventPageXY && !isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh), isMonitoringScrollValue = !0;
}
}
});
module.exports = ReactBrowserEventEmitter;
}, /* 96 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventEmitterMixin
*/
"use strict";
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events), EventPluginHub.processEventQueue(!1);
}
var EventPluginHub = __webpack_require__(20), ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*/
handleTopLevel: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
}, /* 97 */
/***/
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";
/**
* 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 = {};
return 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(), prefixes;
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];
if (!vendorPrefixes[eventName]) return eventName;
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) return prefixedEventNames[eventName] = prefixMap[styleProp];
return "";
}
var ExecutionEnvironment = __webpack_require__(28), vendorPrefixes = {
animationend: makePrefixMap("Animation", "AnimationEnd"),
animationiteration: makePrefixMap("Animation", "AnimationIteration"),
animationstart: makePrefixMap("Animation", "AnimationStart"),
transitionend: makePrefixMap("Transition", "TransitionEnd")
}, prefixedEventNames = {}, style = {};
/**
* Bootstrap if a DOM exists.
*/
ExecutionEnvironment.canUseDOM && (style = document.createElement("div").style,
"AnimationEvent" in window || (delete vendorPrefixes.animationend.animation, delete vendorPrefixes.animationiteration.animation,
delete vendorPrefixes.animationstart.animation), "TransitionEvent" in window || delete vendorPrefixes.transitionend.transition),
module.exports = getVendorPrefixedEventName;
}, /* 98 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMButton
*/
"use strict";
var DisabledInputUtils = __webpack_require__(99), ReactDOMButton = {
getNativeProps: DisabledInputUtils.getNativeProps
};
module.exports = ReactDOMButton;
}, /* 99 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DisabledInputUtils
*/
"use strict";
var disableableMouseListenerNames = {
onClick: !0,
onDoubleClick: !0,
onMouseDown: !0,
onMouseMove: !0,
onMouseUp: !0,
onClickCapture: !0,
onDoubleClickCapture: !0,
onMouseDownCapture: !0,
onMouseMoveCapture: !0,
onMouseUpCapture: !0
}, DisabledInputUtils = {
getNativeProps: function(inst, props) {
if (!props.disabled) return props;
// Copy the props, except the mouse listeners
var nativeProps = {};
for (var key in props) !disableableMouseListenerNames[key] && props.hasOwnProperty(key) && (nativeProps[key] = props[key]);
return nativeProps;
}
};
module.exports = DisabledInputUtils;
}, /* 100 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMInput
*/
"use strict";
function forceUpdateIfMounted() {
this._rootNodeID && // DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
function warnIfValueIsNull(props) {
null == props || null !== props.value || didWarnValueNull || ("production" !== process.env.NODE_ENV ? warning(!1, "`value` prop on `input` should not be null. Consider using the empty string to clear the component or `undefined` for uncontrolled components.") : void 0,
didWarnValueNull = !0);
}
function _handleChange(event) {
var props = this._currentElement.props, returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if ("radio" === props.type && null != name) {
for (var rootNode = ReactDOMComponentTree.getNodeFromInstance(this), queryRoot = rootNode; queryRoot.parentNode; ) queryRoot = queryRoot.parentNode;
for (var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'), i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode !== rootNode && otherNode.form === rootNode.form) {
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React radio buttons with non-React ones.
var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode);
otherInstance ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.") : invariant(!1),
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
}
return returnValue;
}
var _assign = __webpack_require__(30), DisabledInputUtils = __webpack_require__(99), DOMPropertyOperations = __webpack_require__(90), LinkedValueUtils = __webpack_require__(101), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), invariant = __webpack_require__(18), warning = __webpack_require__(24), didWarnValueLink = !1, didWarnCheckedLink = !1, didWarnValueNull = !1, didWarnValueDefaultValue = !1, didWarnCheckedDefaultChecked = !1, didWarnControlledToUncontrolled = !1, didWarnUncontrolledToControlled = !1, ReactDOMInput = {
getNativeProps: function(inst, props) {
var value = LinkedValueUtils.getValue(props), checked = LinkedValueUtils.getChecked(props), nativeProps = _assign({
// Make sure we set .type before any other properties (setting .value
// before .type means .value is lost in IE11 and below)
type: void 0
}, DisabledInputUtils.getNativeProps(inst, props), {
defaultChecked: void 0,
defaultValue: void 0,
value: null != value ? value : inst._wrapperState.initialValue,
checked: null != checked ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function(inst, props) {
if ("production" !== process.env.NODE_ENV) {
LinkedValueUtils.checkPropTypes("input", props, inst._currentElement._owner);
var owner = inst._currentElement._owner;
void 0 === props.valueLink || didWarnValueLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.") : void 0,
didWarnValueLink = !0), void 0 === props.checkedLink || didWarnCheckedLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.") : void 0,
didWarnCheckedLink = !0), void 0 === props.checked || void 0 === props.defaultChecked || didWarnCheckedDefaultChecked || ("production" !== process.env.NODE_ENV ? warning(!1, "%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0,
didWarnCheckedDefaultChecked = !0), void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue || ("production" !== process.env.NODE_ENV ? warning(!1, "%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0,
didWarnValueDefaultValue = !0), warnIfValueIsNull(props);
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.defaultChecked || !1,
initialValue: null != defaultValue ? defaultValue : null,
listeners: null,
onChange: _handleChange.bind(inst)
}, "production" !== process.env.NODE_ENV && (inst._wrapperState.controlled = void 0 !== props.checked || void 0 !== props.value);
},
updateWrapper: function(inst) {
var props = inst._currentElement.props;
if ("production" !== process.env.NODE_ENV) {
warnIfValueIsNull(props);
var initialValue = inst._wrapperState.initialChecked || inst._wrapperState.initialValue, defaultValue = props.defaultChecked || props.defaultValue, controlled = void 0 !== props.checked || void 0 !== props.value, owner = inst._currentElement._owner;
!initialValue && inst._wrapperState.controlled || !controlled || didWarnUncontrolledToControlled || ("production" !== process.env.NODE_ENV ? warning(!1, "%s is changing an uncontrolled input of type %s to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0,
didWarnUncontrolledToControlled = !0), !inst._wrapperState.controlled || !defaultValue && controlled || didWarnControlledToUncontrolled || ("production" !== process.env.NODE_ENV ? warning(!1, "%s is changing a controlled input of type %s to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components", owner && owner.getName() || "A component", props.type) : void 0,
didWarnControlledToUncontrolled = !0);
}
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
null != checked && DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), "checked", checked || !1);
var value = LinkedValueUtils.getValue(props);
null != value && // Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), "value", "" + value);
}
};
module.exports = ReactDOMInput;
}).call(exports, __webpack_require__(17));
}, /* 101 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule LinkedValueUtils
*/
"use strict";
function _assertSingleLink(inputProps) {
null != inputProps.checkedLink && null != inputProps.valueLink ? "production" !== process.env.NODE_ENV ? invariant(!1, "Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don't want to use valueLink and vice versa.") : invariant(!1) : void 0;
}
function _assertValueLink(inputProps) {
_assertSingleLink(inputProps), null != inputProps.value || null != inputProps.onChange ? "production" !== process.env.NODE_ENV ? invariant(!1, "Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don't want to use valueLink.") : invariant(!1) : void 0;
}
function _assertCheckedLink(inputProps) {
_assertSingleLink(inputProps), null != inputProps.checked || null != inputProps.onChange ? "production" !== process.env.NODE_ENV ? invariant(!1, "Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don't want to use checkedLink") : invariant(!1) : void 0;
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) return " Check the render method of `" + name + "`.";
}
return "";
}
var ReactPropTypes = __webpack_require__(102), ReactPropTypeLocations = __webpack_require__(108), invariant = __webpack_require__(18), warning = __webpack_require__(24), hasReadOnlyValue = {
button: !0,
checkbox: !0,
image: !0,
hidden: !0,
radio: !0,
reset: !0,
submit: !0
}, propTypes = {
value: function(props, propName, componentName) {
return !props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled ? null : new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.");
},
checked: function(props, propName, componentName) {
return !props[propName] || props.onChange || props.readOnly || props.disabled ? null : new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.");
},
onChange: ReactPropTypes.func
}, loggedTypeFailures = {}, LinkedValueUtils = {
checkPropTypes: function(tagName, props, owner) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = !0;
var addendum = getDeclarationErrorAddendum(owner);
"production" !== process.env.NODE_ENV ? warning(!1, "Failed form propType: %s%s", error.message, addendum) : void 0;
}
}
},
/**
* @param {object} inputProps Props for form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function(inputProps) {
return inputProps.valueLink ? (_assertValueLink(inputProps), inputProps.valueLink.value) : inputProps.value;
},
/**
* @param {object} inputProps Props for form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function(inputProps) {
return inputProps.checkedLink ? (_assertCheckedLink(inputProps), inputProps.checkedLink.value) : inputProps.checked;
},
/**
* @param {object} inputProps Props for form component
* @param {SyntheticEvent} event change event to handle
*/
executeOnChange: function(inputProps, event) {
return inputProps.valueLink ? (_assertValueLink(inputProps), inputProps.valueLink.requestChange(event.target.value)) : inputProps.checkedLink ? (_assertCheckedLink(inputProps),
inputProps.checkedLink.requestChange(event.target.checked)) : inputProps.onChange ? inputProps.onChange.call(void 0, event) : void 0;
}
};
module.exports = LinkedValueUtils;
}).call(exports, __webpack_require__(17));
}, /* 102 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypes
*/
"use strict";
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
// SameValue algorithm
return x === y ? 0 !== x || 1 / x === 1 / y : x !== x && y !== y;
}
/*eslint-enable no-self-compare*/
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
if (componentName = componentName || ANONYMOUS, propFullName = propFullName || propName,
null == props[propName]) {
var locationName = ReactPropTypeLocationNames[location];
return isRequired ? new Error("Required " + locationName + " `" + propFullName + "` was not specified in " + ("`" + componentName + "`.")) : null;
}
return validate(props, propName, componentName, location, propFullName);
}
var chainedCheckType = checkType.bind(null, !1);
return chainedCheckType.isRequired = checkType.bind(null, !0), chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName], propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location], preciseType = getPreciseType(propValue);
return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if ("function" != typeof typeChecker) return new Error("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location], propType = getPropType(propValue);
return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + "[" + i + "]");
if (error instanceof Error) return error;
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error("Invalid " + locationName + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a single ReactElement."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location], expectedClassName = expectedClass.name || ANONYMOUS, actualClassName = getClassName(props[propName]);
return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
function validate(props, propName, componentName, location, propFullName) {
for (var propValue = props[propName], i = 0; i < expectedValues.length; i++) if (is(propValue, expectedValues[i])) return null;
var locationName = ReactPropTypeLocationNames[location], valuesString = JSON.stringify(expectedValues);
return new Error("Invalid " + locationName + " `" + propFullName + "` of value `" + propValue + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
}
return createChainableTypeChecker(Array.isArray(expectedValues) ? validate : function() {
return new Error("Invalid argument supplied to oneOf, expected an instance of array.");
});
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if ("function" != typeof typeChecker) return new Error("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
var propValue = props[propName], propType = getPropType(propValue);
if ("object" !== propType) {
var locationName = ReactPropTypeLocationNames[location];
return new Error("Invalid " + locationName + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."));
}
for (var key in propValue) if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + "." + key);
if (error instanceof Error) return error;
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (null == checker(props, propName, componentName, location, propFullName)) return null;
}
var locationName = ReactPropTypeLocationNames[location];
return new Error("Invalid " + locationName + " `" + propFullName + "` supplied to " + ("`" + componentName + "`."));
}
return createChainableTypeChecker(Array.isArray(arrayOfTypeCheckers) ? validate : function() {
return new Error("Invalid argument supplied to oneOfType, expected an instance of array.");
});
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error("Invalid " + locationName + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName], propType = getPropType(propValue);
if ("object" !== propType) {
var locationName = ReactPropTypeLocationNames[location];
return new Error("Invalid " + locationName + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (checker) {
var error = checker(propValue, key, componentName, location, propFullName + "." + key);
if (error) return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case "number":
case "string":
case "undefined":
return !0;
case "boolean":
return !propValue;
case "object":
if (Array.isArray(propValue)) return propValue.every(isNode);
if (null === propValue || ReactElement.isValidElement(propValue)) return !0;
var iteratorFn = getIteratorFn(propValue);
if (!iteratorFn) return !1;
var step, iterator = iteratorFn.call(propValue);
if (iteratorFn !== propValue.entries) {
for (;!(step = iterator.next()).done; ) if (!isNode(step.value)) return !1;
} else // Iterator will provide entry [k,v] tuples rather than values.
for (;!(step = iterator.next()).done; ) {
var entry = step.value;
if (entry && !isNode(entry[1])) return !1;
}
return !0;
default:
return !1;
}
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
return Array.isArray(propValue) ? "array" : propValue instanceof RegExp ? "object" : propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if ("object" === propType) {
if (propValue instanceof Date) return "date";
if (propValue instanceof RegExp) return "regexp";
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
return propValue.constructor && propValue.constructor.name ? propValue.constructor.name : ANONYMOUS;
}
var ReactElement = __webpack_require__(103), ReactPropTypeLocationNames = __webpack_require__(106), emptyFunction = __webpack_require__(25), getIteratorFn = __webpack_require__(107), ANONYMOUS = "<<anonymous>>", ReactPropTypes = {
array: createPrimitiveTypeChecker("array"),
bool: createPrimitiveTypeChecker("boolean"),
func: createPrimitiveTypeChecker("function"),
number: createPrimitiveTypeChecker("number"),
object: createPrimitiveTypeChecker("object"),
string: createPrimitiveTypeChecker("string"),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
module.exports = ReactPropTypes;
}, /* 103 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElement
*/
"use strict";
var specialPropKeyWarningShown, specialPropRefWarningShown, _assign = __webpack_require__(30), ReactCurrentOwner = __webpack_require__(104), warning = __webpack_require__(24), canDefineProperty = __webpack_require__(105), REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol["for"] && Symbol["for"]("react.element") || 60103, RESERVED_PROPS = {
key: !0,
ref: !0,
__self: !0,
__source: !0
}, ReactElement = function(type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
// self and source are DEV only properties.
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
return "production" !== process.env.NODE_ENV && (element._store = {}, canDefineProperty ? (Object.defineProperty(element._store, "validated", {
configurable: !1,
enumerable: !1,
writable: !0,
value: !1
}), Object.defineProperty(element, "_self", {
configurable: !1,
enumerable: !1,
writable: !1,
value: self
}), Object.defineProperty(element, "_source", {
configurable: !1,
enumerable: !1,
writable: !1,
value: source
})) : (element._store.validated = !1, element._self = self, element._source = source),
Object.freeze && (Object.freeze(element.props), Object.freeze(element))), element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createelement
*/
ReactElement.createElement = function(type, config, children) {
var propName, props = {}, key = null, ref = null, self = null, source = null;
if (null != config) {
"production" !== process.env.NODE_ENV ? ("production" !== process.env.NODE_ENV ? warning(null == config.__proto__ || config.__proto__ === Object.prototype, "React.createElement(...): Expected props argument to be a plain object. Properties defined in its prototype chain will be ignored.") : void 0,
ref = !config.hasOwnProperty("ref") || Object.getOwnPropertyDescriptor(config, "ref").get ? null : config.ref,
key = !config.hasOwnProperty("key") || Object.getOwnPropertyDescriptor(config, "key").get ? null : "" + config.key) : (ref = void 0 === config.ref ? null : config.ref,
key = void 0 === config.key ? null : "" + config.key), self = void 0 === config.__self ? null : config.__self,
source = void 0 === config.__source ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) 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 (1 === childrenLength) props.children = children; else if (childrenLength > 1) {
for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 2];
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) void 0 === props[propName] && (props[propName] = defaultProps[propName]);
}
// Create dummy `key` and `ref` property to `props` to warn users
// against its use
return "production" !== process.env.NODE_ENV && ("undefined" != typeof props.$$typeof && props.$$typeof === REACT_ELEMENT_TYPE || (props.hasOwnProperty("key") || Object.defineProperty(props, "key", {
get: function() {
specialPropKeyWarningShown || (specialPropKeyWarningShown = !0, "production" !== process.env.NODE_ENV ? warning(!1, "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)", "function" == typeof type && "displayName" in type ? type.displayName : "Element") : void 0);
},
configurable: !0
}), props.hasOwnProperty("ref") || Object.defineProperty(props, "ref", {
get: function() {
specialPropRefWarningShown || (specialPropRefWarningShown = !0, "production" !== process.env.NODE_ENV ? warning(!1, "%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)", "function" == typeof type && "displayName" in type ? type.displayName : "Element") : void 0);
},
configurable: !0
}))), ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}, /**
* Return a function that produces ReactElements of a given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory
*/
ReactElement.createFactory = function(type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
return factory.type = type, factory;
}, ReactElement.cloneAndReplaceKey = function(oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
}, /**
* Clone and return a new ReactElement using element as the starting point.
* See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
*/
ReactElement.cloneElement = function(element, config, children) {
var propName, props = _assign({}, element.props), key = element.key, ref = element.ref, self = element._self, source = element._source, owner = element._owner;
if (null != config) {
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == config.__proto__ || config.__proto__ === Object.prototype, "React.cloneElement(...): Expected props argument to be a plain object. Properties defined in its prototype chain will be ignored.") : void 0),
void 0 !== config.ref && (ref = config.ref, owner = ReactCurrentOwner.current),
void 0 !== config.key && (key = "" + config.key);
// Remaining properties override existing props
var defaultProps;
element.type && element.type.defaultProps && (defaultProps = element.type.defaultProps);
for (propName in config) config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName) && (void 0 === config[propName] && void 0 !== defaultProps ? props[propName] = defaultProps[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 (1 === childrenLength) props.children = children; else if (childrenLength > 1) {
for (var childArray = Array(childrenLength), i = 0; childrenLength > i; i++) childArray[i] = arguments[i + 2];
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}, /**
* Verifies the object is a ReactElement.
* See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function(object) {
return "object" == typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
}, module.exports = ReactElement;
}).call(exports, __webpack_require__(17));
}, /* 104 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCurrentOwner
*/
"use strict";
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
}, /* 105 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule canDefineProperty
*/
"use strict";
var canDefineProperty = !1;
if ("production" !== process.env.NODE_ENV) try {
Object.defineProperty({}, "x", {
get: function() {}
}), canDefineProperty = !0;
} catch (x) {}
module.exports = canDefineProperty;
}).call(exports, __webpack_require__(17));
}, /* 106 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocationNames
*/
"use strict";
var ReactPropTypeLocationNames = {};
"production" !== process.env.NODE_ENV && (ReactPropTypeLocationNames = {
prop: "prop",
context: "context",
childContext: "child context"
}), module.exports = ReactPropTypeLocationNames;
}).call(exports, __webpack_require__(17));
}, /* 107 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getIteratorFn
*/
"use strict";
// Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
return "function" == typeof iteratorFn ? iteratorFn : void 0;
}
/* global Symbol */
var ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator";
module.exports = getIteratorFn;
}, /* 108 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocations
*/
"use strict";
var keyMirror = __webpack_require__(16), ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
}, /* 109 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMOption
*/
"use strict";
var _assign = __webpack_require__(30), ReactChildren = __webpack_require__(110), ReactDOMComponentTree = __webpack_require__(38), ReactDOMSelect = __webpack_require__(113), warning = __webpack_require__(24), ReactDOMOption = {
mountWrapper: function(inst, props, nativeParent) {
// TODO (yungsters): Remove support for `selected` in <option>.
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == props.selected, "Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.") : void 0);
// Look up whether this option is 'selected'
var selectValue = null;
if (null != nativeParent) {
var selectParent = nativeParent;
"optgroup" === selectParent._tag && (selectParent = selectParent._nativeParent),
null != selectParent && "select" === selectParent._tag && (selectValue = ReactDOMSelect.getSelectValueContext(selectParent));
}
// If the value is null (e.g., no specified value or after initial mount)
// or missing (e.g., for <datalist>), we don't change props.selected
var selected = null;
if (null != selectValue) if (selected = !1, Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) if ("" + selectValue[i] == "" + props.value) {
selected = !0;
break;
}
} else selected = "" + selectValue == "" + props.value;
inst._wrapperState = {
selected: selected
};
},
postMountWrapper: function(inst) {
// value="" should make a value attribute (#6219)
var props = inst._currentElement.props;
if (null != props.value) {
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
node.setAttribute("value", props.value);
}
},
getNativeProps: function(inst, props) {
var nativeProps = _assign({
selected: void 0,
children: void 0
}, props);
// Read state only from initial mount because <select> updates value
// manually; we need the initial state only for server rendering
null != inst._wrapperState.selected && (nativeProps.selected = inst._wrapperState.selected);
var content = "";
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
return ReactChildren.forEach(props.children, function(child) {
null != child && ("string" == typeof child || "number" == typeof child ? content += child : "production" !== process.env.NODE_ENV ? warning(!1, "Only strings and numbers are supported as <option> children.") : void 0);
}), content && (nativeProps.children = content), nativeProps;
}
};
module.exports = ReactDOMOption;
}).call(exports, __webpack_require__(17));
}, /* 110 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildren
*/
"use strict";
function escapeUserProvidedKey(text) {
return ("" + text).replace(userProvidedKeyEscapeRegex, "$&/");
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction, this.context = forEachContext, this.count = 0;
}
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func, context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (null == children) return children;
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext), ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult, this.keyPrefix = keyPrefix, this.func = mapFunction, this.context = mapContext,
this.count = 0;
}
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context, mappedChild = func.call(context, child, bookKeeping.count++);
Array.isArray(mappedChild) ? mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument) : null != mappedChild && (ReactElement.isValidElement(mappedChild) && (mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (!mappedChild.key || child && child.key === mappedChild.key ? "" : escapeUserProvidedKey(mappedChild.key) + "/") + childKey)),
result.push(mappedChild));
}
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
var escapedPrefix = "";
null != prefix && (escapedPrefix = escapeUserProvidedKey(prefix) + "/");
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext), MapBookKeeping.release(traverseContext);
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.map
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (null == children) return children;
var result = [];
return mapIntoWithKeyPrefixInternal(children, result, null, func, context), result;
}
function forEachSingleChildDummy(traverseContext, child, name) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.count
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
*/
function toArray(children) {
var result = [];
return mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument),
result;
}
var PooledClass = __webpack_require__(31), ReactElement = __webpack_require__(103), emptyFunction = __webpack_require__(25), traverseAllChildren = __webpack_require__(111), twoArgumentPooler = PooledClass.twoArgumentPooler, fourArgumentPooler = PooledClass.fourArgumentPooler, userProvidedKeyEscapeRegex = /\/+/g;
ForEachBookKeeping.prototype.destructor = function() {
this.func = null, this.context = null, this.count = 0;
}, PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler), MapBookKeeping.prototype.destructor = function() {
this.result = null, this.keyPrefix = null, this.func = null, this.context = null,
this.count = 0;
}, PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
count: countChildren,
toArray: toArray
};
module.exports = ReactChildren;
}, /* 111 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule traverseAllChildren
*/
"use strict";
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
return component && "object" == typeof component && null != component.key ? KeyEscapeUtils.escape(component.key) : index.toString(36);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if ("undefined" !== type && "boolean" !== type || (// All of the above are perceived as null.
children = null), null === children || "string" === type || "number" === type || ReactElement.isValidElement(children)) // If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
return callback(traverseContext, children, "" === nameSoFar ? SEPARATOR + getComponentKey(children, 0) : nameSoFar),
1;
var child, nextName, subtreeCount = 0, nextNamePrefix = "" === nameSoFar ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) for (var i = 0; i < children.length; i++) child = children[i],
nextName = nextNamePrefix + getComponentKey(child, i), subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var step, iterator = iteratorFn.call(children);
if (iteratorFn !== children.entries) for (var ii = 0; !(step = iterator.next()).done; ) child = step.value,
nextName = nextNamePrefix + getComponentKey(child, ii++), subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); else // Iterator will provide entry [k,v] tuples rather than values.
for ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(didWarnAboutMaps, "Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead.") : void 0,
didWarnAboutMaps = !0); !(step = iterator.next()).done; ) {
var entry = step.value;
entry && (child = entry[1], nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0),
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext));
}
} else if ("object" === type) {
var addendum = "";
if ("production" !== process.env.NODE_ENV && (addendum = " If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.",
children._isReactElement && (addendum = " It looks like you're using an element created by a different version of React. Make sure to use only one copy of React."),
ReactCurrentOwner.current)) {
var name = ReactCurrentOwner.current.getName();
name && (addendum += " Check the render method of `" + name + "`.");
}
var childrenString = String(children);
"production" !== process.env.NODE_ENV ? invariant(!1, "Objects are not valid as a React child (found: %s).%s", "[object Object]" === childrenString ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString, addendum) : invariant(!1);
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
return null == children ? 0 : traverseAllChildrenImpl(children, "", callback, traverseContext);
}
var ReactCurrentOwner = __webpack_require__(104), ReactElement = __webpack_require__(103), getIteratorFn = __webpack_require__(107), invariant = __webpack_require__(18), KeyEscapeUtils = __webpack_require__(112), warning = __webpack_require__(24), SEPARATOR = ".", SUBSEPARATOR = ":", didWarnAboutMaps = !1;
module.exports = traverseAllChildren;
}).call(exports, __webpack_require__(17));
}, /* 112 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule KeyEscapeUtils
*/
"use strict";
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {*} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g, escaperLookup = {
"=": "=0",
":": "=2"
}, escapedString = ("" + key).replace(escapeRegex, function(match) {
return escaperLookup[match];
});
return "$" + escapedString;
}
/**
* Unescape and unwrap key for human-readable display
*
* @param {string} key to unescape.
* @return {string} the unescaped key.
*/
function unescape(key) {
var unescapeRegex = /(=0|=2)/g, unescaperLookup = {
"=0": "=",
"=2": ":"
}, keySubstring = "." === key[0] && "$" === key[1] ? key.substring(2) : key.substring(1);
return ("" + keySubstring).replace(unescapeRegex, function(match) {
return unescaperLookup[match];
});
}
var KeyEscapeUtils = {
escape: escape,
unescape: unescape
};
module.exports = KeyEscapeUtils;
}, /* 113 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelect
*/
"use strict";
function updateOptionsIfPendingUpdateAndMounted() {
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
this._wrapperState.pendingUpdate = !1;
var props = this._currentElement.props, value = LinkedValueUtils.getValue(props);
null != value && updateOptions(this, Boolean(props.multiple), value);
}
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) return " Check the render method of `" + name + "`.";
}
return "";
}
function warnIfValueIsNull(props) {
null == props || null !== props.value || didWarnValueNull || ("production" !== process.env.NODE_ENV ? warning(!1, "`value` prop on `select` should not be null. Consider using the empty string to clear the component or `undefined` for uncontrolled components.") : void 0,
didWarnValueNull = !0);
}
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function checkSelectPropTypes(inst, props) {
var owner = inst._currentElement._owner;
LinkedValueUtils.checkPropTypes("select", props, owner), void 0 === props.valueLink || didWarnValueLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.") : void 0,
didWarnValueLink = !0);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
null != props[propName] && (props.multiple ? "production" !== process.env.NODE_ENV ? warning(Array.isArray(props[propName]), "The `%s` prop supplied to <select> must be an array if `multiple` is true.%s", propName, getDeclarationErrorAddendum(owner)) : void 0 : "production" !== process.env.NODE_ENV ? warning(!Array.isArray(props[propName]), "The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s", propName, getDeclarationErrorAddendum(owner)) : void 0);
}
}
/**
* @param {ReactDOMComponent} inst
* @param {boolean} multiple
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(inst, multiple, propValue) {
var selectedValue, i, options = ReactDOMComponentTree.getNodeFromInstance(inst).options;
if (multiple) {
for (selectedValue = {}, i = 0; i < propValue.length; i++) selectedValue["" + propValue[i]] = !0;
for (i = 0; i < options.length; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
options[i].selected !== selected && (options[i].selected = selected);
}
} else {
for (selectedValue = "" + propValue, i = 0; i < options.length; i++) if (options[i].value === selectedValue) return void (options[i].selected = !0);
options.length && (options[0].selected = !0);
}
}
function _handleChange(event) {
var props = this._currentElement.props, returnValue = LinkedValueUtils.executeOnChange(props, event);
return this._rootNodeID && (this._wrapperState.pendingUpdate = !0), ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this),
returnValue;
}
var _assign = __webpack_require__(30), DisabledInputUtils = __webpack_require__(99), LinkedValueUtils = __webpack_require__(101), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), warning = __webpack_require__(24), didWarnValueLink = !1, didWarnValueNull = !1, didWarnValueDefaultValue = !1, valuePropNames = [ "value", "defaultValue" ], ReactDOMSelect = {
getNativeProps: function(inst, props) {
return _assign({}, DisabledInputUtils.getNativeProps(inst, props), {
onChange: inst._wrapperState.onChange,
value: void 0
});
},
mountWrapper: function(inst, props) {
"production" !== process.env.NODE_ENV && (checkSelectPropTypes(inst, props), warnIfValueIsNull(props));
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
pendingUpdate: !1,
initialValue: null != value ? value : props.defaultValue,
listeners: null,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
}, void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue || ("production" !== process.env.NODE_ENV ? warning(!1, "Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://fb.me/react-controlled-components") : void 0,
didWarnValueDefaultValue = !0);
},
getSelectValueContext: function(inst) {
// ReactDOMOption looks at this initial value so the initial generated
// markup has correct `selected` attributes
return inst._wrapperState.initialValue;
},
postUpdateWrapper: function(inst) {
var props = inst._currentElement.props;
"production" !== process.env.NODE_ENV && warnIfValueIsNull(props), // After the initial mount, we control selected-ness manually so don't pass
// this value down
inst._wrapperState.initialValue = void 0;
var wasMultiple = inst._wrapperState.wasMultiple;
inst._wrapperState.wasMultiple = Boolean(props.multiple);
var value = LinkedValueUtils.getValue(props);
null != value ? (inst._wrapperState.pendingUpdate = !1, updateOptions(inst, Boolean(props.multiple), value)) : wasMultiple !== Boolean(props.multiple) && (// For simplicity, reapply `defaultValue` if `multiple` is toggled.
null != props.defaultValue ? updateOptions(inst, Boolean(props.multiple), props.defaultValue) : updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ""));
}
};
module.exports = ReactDOMSelect;
}).call(exports, __webpack_require__(17));
}, /* 114 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextarea
*/
"use strict";
function forceUpdateIfMounted() {
this._rootNodeID && // DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
function warnIfValueIsNull(props) {
null == props || null !== props.value || didWarnValueNull || ("production" !== process.env.NODE_ENV ? warning(!1, "`value` prop on `textarea` should not be null. Consider using the empty string to clear the component or `undefined` for uncontrolled components.") : void 0,
didWarnValueNull = !0);
}
function _handleChange(event) {
var props = this._currentElement.props, returnValue = LinkedValueUtils.executeOnChange(props, event);
return ReactUpdates.asap(forceUpdateIfMounted, this), returnValue;
}
var _assign = __webpack_require__(30), DisabledInputUtils = __webpack_require__(99), DOMPropertyOperations = __webpack_require__(90), LinkedValueUtils = __webpack_require__(101), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), invariant = __webpack_require__(18), warning = __webpack_require__(24), didWarnValueLink = !1, didWarnValueNull = !1, didWarnValDefaultVal = !1, ReactDOMTextarea = {
getNativeProps: function(inst, props) {
null != props.dangerouslySetInnerHTML ? "production" !== process.env.NODE_ENV ? invariant(!1, "`dangerouslySetInnerHTML` does not make sense on <textarea>.") : invariant(!1) : void 0;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
var nativeProps = _assign({}, DisabledInputUtils.getNativeProps(inst, props), {
defaultValue: void 0,
value: void 0,
children: inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function(inst, props) {
"production" !== process.env.NODE_ENV && (LinkedValueUtils.checkPropTypes("textarea", props, inst._currentElement._owner),
void 0 === props.valueLink || didWarnValueLink || ("production" !== process.env.NODE_ENV ? warning(!1, "`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.") : void 0,
didWarnValueLink = !0), void 0 === props.value || void 0 === props.defaultValue || didWarnValDefaultVal || ("production" !== process.env.NODE_ENV ? warning(!1, "Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://fb.me/react-controlled-components") : void 0,
didWarnValDefaultVal = !0), warnIfValueIsNull(props));
var defaultValue = props.defaultValue, children = props.children;
null != children && ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!1, "Use the `defaultValue` or `value` props instead of setting children on <textarea>.") : void 0),
null != defaultValue ? "production" !== process.env.NODE_ENV ? invariant(!1, "If you supply `defaultValue` on a <textarea>, do not pass children.") : invariant(!1) : void 0,
Array.isArray(children) && (children.length <= 1 ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "<textarea> can only have at most one child.") : invariant(!1),
children = children[0]), defaultValue = "" + children), null == defaultValue && (defaultValue = "");
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: "" + (null != value ? value : defaultValue),
listeners: null,
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function(inst) {
var props = inst._currentElement.props;
"production" !== process.env.NODE_ENV && warnIfValueIsNull(props);
var value = LinkedValueUtils.getValue(props);
null != value && // Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), "value", "" + value);
}
};
module.exports = ReactDOMTextarea;
}).call(exports, __webpack_require__(17));
}, /* 115 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChild
*/
"use strict";
/**
* Make an update for markup to be rendered and inserted at a supplied index.
*
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function makeInsertMarkup(markup, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for moving an existing element to another index.
*
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function makeMove(child, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler.getNativeNode(child),
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for removing an element at an index.
*
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function makeRemove(child, node) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
content: null,
fromIndex: child._mountIndex,
fromNode: node,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the markup of a node.
*
* @param {string} markup Markup that renders into an element.
* @private
*/
function makeSetMarkup(markup) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.SET_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the text content.
*
* @param {string} textContent Text content to set.
* @private
*/
function makeTextContent(textContent) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
content: textContent,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Push an update, if any, onto the queue. Creates a new queue if none is
* passed and always returns the queue. Mutative.
*/
function enqueue(queue, update) {
return update && (queue = queue || [], queue.push(update)), queue;
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue(inst, updateQueue) {
ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue);
}
var ReactComponentEnvironment = __webpack_require__(116), ReactInstrumentation = __webpack_require__(44), ReactMultiChildUpdateTypes = __webpack_require__(77), ReactCurrentOwner = __webpack_require__(104), ReactReconciler = __webpack_require__(51), ReactChildReconciler = __webpack_require__(117), emptyFunction = __webpack_require__(25), flattenChildren = __webpack_require__(127), invariant = __webpack_require__(18), setChildrenForInstrumentation = emptyFunction;
"production" !== process.env.NODE_ENV && (setChildrenForInstrumentation = function(children) {
ReactInstrumentation.debugTool.onSetChildren(this._debugID, children ? Object.keys(children).map(function(key) {
return children[key]._debugID;
}) : []);
});
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
_reconcilerInstantiateChildren: function(nestedChildren, transaction, context) {
if ("production" !== process.env.NODE_ENV && this._currentElement) try {
return ReactCurrentOwner.current = this._currentElement._owner, ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
} finally {
ReactCurrentOwner.current = null;
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function(prevChildren, nextNestedChildrenElements, removedNodes, transaction, context) {
var nextChildren;
if ("production" !== process.env.NODE_ENV && this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner, nextChildren = flattenChildren(nextNestedChildrenElements);
} finally {
ReactCurrentOwner.current = null;
}
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context),
nextChildren;
}
return nextChildren = flattenChildren(nextNestedChildrenElements), ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context),
nextChildren;
},
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function(nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [], index = 0;
for (var name in children) if (children.hasOwnProperty(name)) {
var child = children[name], mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context);
child._mountIndex = index++, mountImages.push(mountImage);
}
return "production" !== process.env.NODE_ENV && setChildrenForInstrumentation.call(this, children),
mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function(nextContent) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, !1);
for (var name in prevChildren) prevChildren.hasOwnProperty(name) && ("production" !== process.env.NODE_ENV ? invariant(!1, "updateTextContent called on non-empty component.") : invariant(!1));
// Set new text content.
var updates = [ makeTextContent(nextContent) ];
processQueue(this, updates);
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function(nextMarkup) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, !1);
for (var name in prevChildren) prevChildren.hasOwnProperty(name) && ("production" !== process.env.NODE_ENV ? invariant(!1, "updateTextContent called on non-empty component.") : invariant(!1));
var updates = [ makeSetMarkup(nextMarkup) ];
processQueue(this, updates);
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildrenElements, transaction, context) {
// Hook used by React ART
this._updateChildren(nextNestedChildrenElements, transaction, context);
},
/**
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function(nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren, removedNodes = {}, nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, removedNodes, transaction, context);
if (nextChildren || prevChildren) {
var name, updates = null, lastIndex = 0, nextIndex = 0, lastPlacedNode = null;
for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) {
var prevChild = prevChildren && prevChildren[name], nextChild = nextChildren[name];
prevChild === nextChild ? (updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)),
lastIndex = Math.max(prevChild._mountIndex, lastIndex), prevChild._mountIndex = nextIndex) : (prevChild && (// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex)), // The child must be instantiated before it's mounted.
updates = enqueue(updates, this._mountChildAtIndex(nextChild, lastPlacedNode, nextIndex, transaction, context))),
nextIndex++, lastPlacedNode = ReactReconciler.getNativeNode(nextChild);
}
// Remove children that are no longer present.
for (name in removedNodes) removedNodes.hasOwnProperty(name) && (updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])));
updates && processQueue(this, updates), this._renderedChildren = nextChildren, "production" !== process.env.NODE_ENV && setChildrenForInstrumentation.call(this, nextChildren);
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted. It does not actually perform any
* backend operations.
*
* @internal
*/
unmountChildren: function(safely) {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren, safely), this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function(child, afterNode, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
return child._mountIndex < lastIndex ? makeMove(child, afterNode, toIndex) : void 0;
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function(child, afterNode, mountImage) {
return makeInsertMarkup(mountImage, afterNode, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function(child, node) {
return makeRemove(child, node);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildAtIndex: function(child, afterNode, index, transaction, context) {
var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context);
return child._mountIndex = index, this.createChild(child, afterNode, mountImage);
},
/**
* Unmounts a rendered child.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @private
*/
_unmountChild: function(child, node) {
var update = this.removeChild(child, node);
return child._mountIndex = null, update;
}
}
};
module.exports = ReactMultiChild;
}).call(exports, __webpack_require__(17));
}, /* 116 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentEnvironment
*/
"use strict";
var invariant = __webpack_require__(18), injected = !1, ReactComponentEnvironment = {
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*/
unmountIDFromEnvironment: null,
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkup: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function(environment) {
injected ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactCompositeComponent: injectEnvironment() can only be called once.") : invariant(!1) : void 0,
ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment,
ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup,
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates,
injected = !0;
}
}
};
module.exports = ReactComponentEnvironment;
}).call(exports, __webpack_require__(17));
}, /* 117 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildReconciler
*/
"use strict";
function instantiateChild(childInstances, child, name) {
// We found a component instance.
var keyUnique = void 0 === childInstances[name];
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(keyUnique, "flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.", KeyEscapeUtils.unescape(name)) : void 0),
null != child && keyUnique && (childInstances[name] = instantiateReactComponent(child));
}
var ReactReconciler = __webpack_require__(51), instantiateReactComponent = __webpack_require__(118), KeyEscapeUtils = __webpack_require__(112), shouldUpdateReactComponent = __webpack_require__(124), traverseAllChildren = __webpack_require__(111), warning = __webpack_require__(24), ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function(nestedChildNodes, transaction, context) {
if (null == nestedChildNodes) return null;
var childInstances = {};
return traverseAllChildren(nestedChildNodes, instantiateChild, childInstances),
childInstances;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextChildren Flat child element maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function(prevChildren, nextChildren, removedNodes, transaction, context) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
if (nextChildren || prevChildren) {
var name, prevChild;
for (name in nextChildren) if (nextChildren.hasOwnProperty(name)) {
prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement, nextElement = nextChildren[name];
if (null != prevChild && shouldUpdateReactComponent(prevElement, nextElement)) ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context),
nextChildren[name] = prevChild; else {
prevChild && (removedNodes[name] = ReactReconciler.getNativeNode(prevChild), ReactReconciler.unmountComponent(prevChild, !1));
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement);
nextChildren[name] = nextChildInstance;
}
}
// Unmount children that are no longer present.
for (name in prevChildren) !prevChildren.hasOwnProperty(name) || nextChildren && nextChildren.hasOwnProperty(name) || (prevChild = prevChildren[name],
removedNodes[name] = ReactReconciler.getNativeNode(prevChild), ReactReconciler.unmountComponent(prevChild, !1));
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function(renderedChildren, safely) {
for (var name in renderedChildren) if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild, safely);
}
}
};
module.exports = ReactChildReconciler;
}).call(exports, __webpack_require__(17));
}, /* 118 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule instantiateReactComponent
*/
"use strict";
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) return " Check the render method of `" + name + "`.";
}
return "";
}
function getDisplayName(instance) {
var element = instance._currentElement;
return null == element ? "#empty" : "string" == typeof element || "number" == typeof element ? "#text" : "string" == typeof element.type ? element.type : instance.getName ? instance.getName() || "Unknown" : element.type.displayName || element.type.name || "Unknown";
}
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return "function" == typeof type && "undefined" != typeof type.prototype && "function" == typeof type.prototype.mountComponent && "function" == typeof type.prototype.receiveComponent;
}
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node) {
var instance, isEmpty = null === node || node === !1;
if (isEmpty) instance = ReactEmptyComponent.create(instantiateReactComponent); else if ("object" == typeof node) {
var element = node;
!element || "function" != typeof element.type && "string" != typeof element.type ? "production" !== process.env.NODE_ENV ? invariant(!1, "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", null == element.type ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(!1) : void 0,
// Special case string values
instance = "string" == typeof element.type ? ReactNativeComponent.createInternalComponent(element) : isInternalComponentType(element.type) ? new element.type(element) : new ReactCompositeComponentWrapper(element);
} else "string" == typeof node || "number" == typeof node ? instance = ReactNativeComponent.createInstanceForText(node) : "production" !== process.env.NODE_ENV ? invariant(!1, "Encountered invalid React node of type %s", typeof node) : invariant(!1);
if ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning("function" == typeof instance.mountComponent && "function" == typeof instance.receiveComponent && "function" == typeof instance.getNativeNode && "function" == typeof instance.unmountComponent, "Only React Components can be mounted.") : void 0),
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0, instance._mountImage = null, "production" !== process.env.NODE_ENV && (instance._isOwnerNecessary = !1,
instance._warnedAboutRefsInRender = !1), "production" !== process.env.NODE_ENV) {
var debugID = isEmpty ? 0 : nextDebugID++;
if (instance._debugID = debugID, 0 !== debugID) {
var displayName = getDisplayName(instance);
ReactInstrumentation.debugTool.onSetDisplayName(debugID, displayName);
var owner = node && node._owner;
owner && ReactInstrumentation.debugTool.onSetOwner(debugID, owner._debugID);
}
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
return "production" !== process.env.NODE_ENV && Object.preventExtensions && Object.preventExtensions(instance),
instance;
}
var _assign = __webpack_require__(30), ReactCompositeComponent = __webpack_require__(119), ReactEmptyComponent = __webpack_require__(125), ReactNativeComponent = __webpack_require__(126), ReactInstrumentation = __webpack_require__(44), invariant = __webpack_require__(18), warning = __webpack_require__(24), ReactCompositeComponentWrapper = function(element) {
this.construct(element);
};
_assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
_instantiateReactComponent: instantiateReactComponent
});
var nextDebugID = 1;
module.exports = instantiateReactComponent;
}).call(exports, __webpack_require__(17));
}, /* 119 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCompositeComponent
*/
"use strict";
function getDeclarationErrorAddendum(component) {
var owner = component._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) return " Check the render method of `" + name + "`.";
}
return "";
}
function StatelessComponent(Component) {}
function warnIfInvalidElement(Component, element) {
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null === element || element === !1 || ReactElement.isValidElement(element), "%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.", Component.displayName || Component.name || "Component") : void 0);
}
function invokeComponentDidMountWithTimer() {
var publicInstance = this._instance;
0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentDidMount"),
publicInstance.componentDidMount(), 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentDidMount");
}
function invokeComponentDidUpdateWithTimer(prevProps, prevState, prevContext) {
var publicInstance = this._instance;
0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentDidUpdate"),
publicInstance.componentDidUpdate(prevProps, prevState, prevContext), 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentDidUpdate");
}
function shouldConstruct(Component) {
return Component.prototype && Component.prototype.isReactComponent;
}
var _assign = __webpack_require__(30), ReactComponentEnvironment = __webpack_require__(116), ReactCurrentOwner = __webpack_require__(104), ReactElement = __webpack_require__(103), ReactErrorUtils = __webpack_require__(23), ReactInstanceMap = __webpack_require__(120), ReactInstrumentation = __webpack_require__(44), ReactNodeTypes = __webpack_require__(121), ReactPropTypeLocations = __webpack_require__(108), ReactPropTypeLocationNames = __webpack_require__(106), ReactReconciler = __webpack_require__(51), ReactUpdateQueue = __webpack_require__(122), emptyObject = __webpack_require__(123), invariant = __webpack_require__(18), shouldUpdateReactComponent = __webpack_require__(124), warning = __webpack_require__(24);
StatelessComponent.prototype.render = function() {
var Component = ReactInstanceMap.get(this)._currentElement.type, element = Component(this.props, this.context, this.updater);
return warnIfInvalidElement(Component, element), element;
};
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1, ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function(element) {
this._currentElement = element, this._rootNodeID = null, this._instance = null,
this._nativeParent = null, this._nativeContainerInfo = null, // See ReactUpdateQueue
this._updateBatchNumber = null, this._pendingElement = null, this._pendingStateQueue = null,
this._pendingReplaceState = !1, this._pendingForceUpdate = !1, this._renderedNodeType = null,
this._renderedComponent = null, this._context = null, this._mountOrder = 0, this._topLevelWrapper = null,
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null, // ComponentWillUnmount shall only be called once
this._calledComponentWillUnmount = !1;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} nativeParent
* @param {?object} nativeContainerInfo
* @param {?object} context
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) {
this._context = context, this._mountOrder = nextMountID++, this._nativeParent = nativeParent,
this._nativeContainerInfo = nativeContainerInfo;
var renderedElement, publicProps = this._processProps(this._currentElement.props), publicContext = this._processContext(context), Component = this._currentElement.type, inst = this._constructComponent(publicProps, publicContext);
if (// Support functional components
shouldConstruct(Component) || null != inst && null != inst.render || (renderedElement = inst,
warnIfInvalidElement(Component, renderedElement), null === inst || inst === !1 || ReactElement.isValidElement(inst) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.", Component.displayName || Component.name || "Component") : invariant(!1),
inst = new StatelessComponent(Component)), "production" !== process.env.NODE_ENV) {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
null == inst.render && ("production" !== process.env.NODE_ENV ? warning(!1, "%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", Component.displayName || Component.name || "Component") : void 0);
var propsMutated = inst.props !== publicProps, componentName = Component.displayName || Component.name || "Component";
"production" !== process.env.NODE_ENV ? warning(void 0 === inst.props || !propsMutated, "%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", componentName, componentName) : void 0;
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps, inst.context = publicContext, inst.refs = emptyObject,
inst.updater = ReactUpdateQueue, this._instance = inst, // Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this), "production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", this.getName() || "a component") : void 0,
"production" !== process.env.NODE_ENV ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", this.getName() || "a component") : void 0,
"production" !== process.env.NODE_ENV ? warning(!inst.propTypes, "propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", this.getName() || "a component") : void 0,
"production" !== process.env.NODE_ENV ? warning(!inst.contextTypes, "contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", this.getName() || "a component") : void 0,
"production" !== process.env.NODE_ENV ? warning("function" != typeof inst.componentShouldUpdate, "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", this.getName() || "A component") : void 0,
"production" !== process.env.NODE_ENV ? warning("function" != typeof inst.componentDidUnmount, "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", this.getName() || "A component") : void 0,
"production" !== process.env.NODE_ENV ? warning("function" != typeof inst.componentWillRecieveProps, "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", this.getName() || "A component") : void 0);
var initialState = inst.state;
void 0 === initialState && (inst.state = initialState = null), "object" != typeof initialState || Array.isArray(initialState) ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s.state: must be set to an object or null", this.getName() || "ReactCompositeComponent") : invariant(!1) : void 0,
this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1;
var markup;
return markup = inst.unstable_handleError ? this.performInitialMountWithErrorHandling(renderedElement, nativeParent, nativeContainerInfo, transaction, context) : this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context),
inst.componentDidMount && ("production" !== process.env.NODE_ENV ? transaction.getReactMountReady().enqueue(invokeComponentDidMountWithTimer, this) : transaction.getReactMountReady().enqueue(inst.componentDidMount, inst)),
markup;
},
_constructComponent: function(publicProps, publicContext) {
if ("production" === process.env.NODE_ENV) return this._constructComponentWithoutOwner(publicProps, publicContext);
ReactCurrentOwner.current = this;
try {
return this._constructComponentWithoutOwner(publicProps, publicContext);
} finally {
ReactCurrentOwner.current = null;
}
},
_constructComponentWithoutOwner: function(publicProps, publicContext) {
var instanceOrElement, Component = this._currentElement.type;
// This can still be an instance in case of factory components
// but we'll count this as time spent rendering as the more common case.
return shouldConstruct(Component) ? ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "ctor"),
instanceOrElement = new Component(publicProps, publicContext, ReactUpdateQueue),
"production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "ctor")) : ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "render"),
instanceOrElement = Component(publicProps, publicContext, ReactUpdateQueue), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "render")),
instanceOrElement;
},
performInitialMountWithErrorHandling: function(renderedElement, nativeParent, nativeContainerInfo, transaction, context) {
var markup, checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context);
} catch (e) {
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint), this._instance.unstable_handleError(e), this._pendingStateQueue && (this._instance.state = this._processPendingState(this._instance.props, this._instance.context)),
checkpoint = transaction.checkpoint(), this._renderedComponent.unmountComponent(!0),
transaction.rollback(checkpoint), // Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context);
}
return markup;
},
performInitialMount: function(renderedElement, nativeParent, nativeContainerInfo, transaction, context) {
var inst = this._instance;
inst.componentWillMount && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillMount"),
inst.componentWillMount(), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillMount"),
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
this._pendingStateQueue && (inst.state = this._processPendingState(inst.props, inst.context))),
// If not a stateless component, we now render
void 0 === renderedElement && (renderedElement = this._renderValidatedComponent()),
this._renderedNodeType = ReactNodeTypes.getType(renderedElement), this._renderedComponent = this._instantiateReactComponent(renderedElement);
var markup = ReactReconciler.mountComponent(this._renderedComponent, transaction, nativeParent, nativeContainerInfo, this._processChildContext(context));
return "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onSetChildren(this._debugID, 0 !== this._renderedComponent._debugID ? [ this._renderedComponent._debugID ] : []),
markup;
},
getNativeNode: function() {
return ReactReconciler.getNativeNode(this._renderedComponent);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function(safely) {
if (this._renderedComponent) {
var inst = this._instance;
if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) {
if (inst._calledComponentWillUnmount = !0, "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillUnmount"),
safely) {
var name = this.getName() + ".componentWillUnmount()";
ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
} else inst.componentWillUnmount();
"production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillUnmount");
}
this._renderedComponent && (ReactReconciler.unmountComponent(this._renderedComponent, safely),
this._renderedNodeType = null, this._renderedComponent = null, this._instance = null),
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null, this._pendingReplaceState = !1, this._pendingForceUpdate = !1,
this._pendingCallbacks = null, this._pendingElement = null, // These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null, this._rootNodeID = null, this._topLevelWrapper = null, // Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
}
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function(context) {
var Component = this._currentElement.type, contextTypes = Component.contextTypes;
if (!contextTypes) return emptyObject;
var maskedContext = {};
for (var contextName in contextTypes) maskedContext[contextName] = context[contextName];
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function(context) {
var maskedContext = this._maskContext(context);
if ("production" !== process.env.NODE_ENV) {
var Component = this._currentElement.type;
Component.contextTypes && this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context);
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var Component = this._currentElement.type, inst = this._instance;
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onBeginProcessingChildContext();
var childContext = inst.getChildContext && inst.getChildContext();
if ("production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onEndProcessingChildContext(),
childContext) {
"object" != typeof Component.childContextTypes ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", this.getName() || "ReactCompositeComponent") : invariant(!1) : void 0,
"production" !== process.env.NODE_ENV && this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext);
for (var name in childContext) name in Component.childContextTypes ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || "ReactCompositeComponent", name) : invariant(!1);
return _assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function(newProps) {
if ("production" !== process.env.NODE_ENV) {
var Component = this._currentElement.type;
Component.propTypes && this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop);
}
return newProps;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function(propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.getName();
for (var propName in propTypes) if (propTypes.hasOwnProperty(propName)) {
var error;
try {
"function" != typeof propTypes[propName] ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.", componentName || "React class", ReactPropTypeLocationNames[location], propName) : invariant(!1) : void 0,
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// top-level render calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
location === ReactPropTypeLocations.prop ? "production" !== process.env.NODE_ENV ? warning(!1, "Failed Composite propType: %s%s", error.message, addendum) : void 0 : "production" !== process.env.NODE_ENV ? warning(!1, "Failed Context Types: %s%s", error.message, addendum) : void 0;
}
}
},
receiveComponent: function(nextElement, transaction, nextContext) {
var prevElement = this._currentElement, prevContext = this._context;
this._pendingElement = null, this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
null != this._pendingElement ? ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context) : null !== this._pendingStateQueue || this._pendingForceUpdate ? this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context) : this._updateBatchNumber = null;
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function(transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var nextContext, nextProps, inst = this._instance, willReceive = !1;
// Determine if the context has changed or not
this._context === nextUnmaskedContext ? nextContext = inst.context : (nextContext = this._processContext(nextUnmaskedContext),
willReceive = !0), // Distinguish between a props update versus a simple state update
prevParentElement === nextParentElement ? // Skip checking prop types again -- we don't read inst.props to avoid
// warning for DOM component props in this upgrade
nextProps = nextParentElement.props : (nextProps = this._processProps(nextParentElement.props),
willReceive = !0), // An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
willReceive && inst.componentWillReceiveProps && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillReceiveProps"),
inst.componentWillReceiveProps(nextProps, nextContext), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillReceiveProps"));
var nextState = this._processPendingState(nextProps, nextContext), shouldUpdate = !0;
!this._pendingForceUpdate && inst.shouldComponentUpdate && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "shouldComponentUpdate"),
shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "shouldComponentUpdate")),
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(void 0 !== shouldUpdate, "%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", this.getName() || "ReactCompositeComponent") : void 0),
this._updateBatchNumber = null, shouldUpdate ? (this._pendingForceUpdate = !1, // Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext)) : (// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement, this._context = nextUnmaskedContext, inst.props = nextProps,
inst.state = nextState, inst.context = nextContext);
},
_processPendingState: function(props, context) {
var inst = this._instance, queue = this._pendingStateQueue, replace = this._pendingReplaceState;
if (this._pendingReplaceState = !1, this._pendingStateQueue = null, !queue) return inst.state;
if (replace && 1 === queue.length) return queue[0];
for (var nextState = _assign({}, replace ? queue[0] : inst.state), i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
_assign(nextState, "function" == typeof partial ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function(nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var prevProps, prevState, prevContext, inst = this._instance, hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
hasComponentDidUpdate && (prevProps = inst.props, prevState = inst.state, prevContext = inst.context),
inst.componentWillUpdate && ("production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "componentWillUpdate"),
inst.componentWillUpdate(nextProps, nextState, nextContext), "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "componentWillUpdate")),
this._currentElement = nextElement, this._context = unmaskedContext, inst.props = nextProps,
inst.state = nextState, inst.context = nextContext, this._updateRenderedComponent(transaction, unmaskedContext),
hasComponentDidUpdate && ("production" !== process.env.NODE_ENV ? transaction.getReactMountReady().enqueue(invokeComponentDidUpdateWithTimer.bind(this, prevProps, prevState, prevContext), this) : transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst));
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function(transaction, context) {
var prevComponentInstance = this._renderedComponent, prevRenderedElement = prevComponentInstance._currentElement, nextRenderedElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); else {
var oldNativeNode = ReactReconciler.getNativeNode(prevComponentInstance);
ReactReconciler.unmountComponent(prevComponentInstance, !1), this._renderedNodeType = ReactNodeTypes.getType(nextRenderedElement),
this._renderedComponent = this._instantiateReactComponent(nextRenderedElement);
var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, transaction, this._nativeParent, this._nativeContainerInfo, this._processChildContext(context));
"production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onSetChildren(this._debugID, 0 !== this._renderedComponent._debugID ? [ this._renderedComponent._debugID ] : []),
this._replaceNodeWithMarkup(oldNativeNode, nextMarkup, prevComponentInstance);
}
},
/**
* Overridden in shallow rendering.
*
* @protected
*/
_replaceNodeWithMarkup: function(oldNativeNode, nextMarkup, prevInstance) {
ReactComponentEnvironment.replaceNodeWithMarkup(oldNativeNode, nextMarkup, prevInstance);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function() {
var inst = this._instance;
"production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onBeginLifeCycleTimer(this._debugID, "render");
var renderedComponent = inst.render();
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
return "production" !== process.env.NODE_ENV && 0 !== this._debugID && ReactInstrumentation.debugTool.onEndLifeCycleTimer(this._debugID, "render"),
"production" !== process.env.NODE_ENV && void 0 === renderedComponent && inst.render._isMockFunction && (renderedComponent = null),
renderedComponent;
},
/**
* @private
*/
_renderValidatedComponent: function() {
var renderedComponent;
ReactCurrentOwner.current = this;
try {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
// TODO: An `isValidNode` function would probably be more appropriate
return null === renderedComponent || renderedComponent === !1 || ReactElement.isValidElement(renderedComponent) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.", this.getName() || "ReactCompositeComponent") : invariant(!1),
renderedComponent;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function(ref, component) {
var inst = this.getPublicInstance();
null == inst ? "production" !== process.env.NODE_ENV ? invariant(!1, "Stateless function components cannot have refs.") : invariant(!1) : void 0;
var publicComponentInstance = component.getPublicInstance();
if ("production" !== process.env.NODE_ENV) {
var componentName = component && component.getName ? component.getName() : "a component";
"production" !== process.env.NODE_ENV ? warning(null != publicComponentInstance, 'Stateless function components cannot be given refs (See ref "%s" in %s created by %s). Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function() {
var type = this._currentElement.type, constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function() {
var inst = this._instance;
return inst instanceof StatelessComponent ? null : inst;
},
// Stub
_instantiateReactComponent: null
}, ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
}).call(exports, __webpack_require__(17));
}, /* 120 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstanceMap
*/
"use strict";
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function(key) {
key._reactInternalInstance = void 0;
},
get: function(key) {
return key._reactInternalInstance;
},
has: function(key) {
return void 0 !== key._reactInternalInstance;
},
set: function(key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
}, /* 121 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNodeTypes
*/
"use strict";
var ReactElement = __webpack_require__(103), invariant = __webpack_require__(18), ReactNodeTypes = {
NATIVE: 0,
COMPOSITE: 1,
EMPTY: 2,
getType: function(node) {
return null === node || node === !1 ? ReactNodeTypes.EMPTY : ReactElement.isValidElement(node) ? "function" == typeof node.type ? ReactNodeTypes.COMPOSITE : ReactNodeTypes.NATIVE : void ("production" !== process.env.NODE_ENV ? invariant(!1, "Unexpected node: %s", node) : invariant(!1));
}
};
module.exports = ReactNodeTypes;
}).call(exports, __webpack_require__(17));
}, /* 122 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdateQueue
*/
"use strict";
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function formatUnexpectedArgument(arg) {
var type = typeof arg;
if ("object" !== type) return type;
var displayName = arg.constructor && arg.constructor.name || type, keys = Object.keys(arg);
return keys.length > 0 && keys.length < 20 ? displayName + " (keys: " + keys.join(", ") + ")" : displayName;
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
return internalInstance ? ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(null == ReactCurrentOwner.current, "%s(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.", callerName) : void 0),
internalInstance) : ("production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!callerName, "%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.", callerName, callerName, publicInstance.constructor.displayName) : void 0),
null);
}
var ReactCurrentOwner = __webpack_require__(104), ReactInstanceMap = __webpack_require__(120), ReactUpdates = __webpack_require__(41), invariant = __webpack_require__(18), warning = __webpack_require__(24), ReactUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function(publicInstance) {
if ("production" !== process.env.NODE_ENV) {
var owner = ReactCurrentOwner.current;
null !== owner && ("production" !== process.env.NODE_ENV ? warning(owner._warnedAboutRefsInRender, "%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", owner.getName() || "A component") : void 0,
owner._warnedAboutRefsInRender = !0);
}
var internalInstance = ReactInstanceMap.get(publicInstance);
return internalInstance ? !!internalInstance._renderedComponent : !1;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @param {string} callerName Name of the calling function in the public API.
* @internal
*/
enqueueCallback: function(publicInstance, callback, callerName) {
ReactUpdateQueue.validateCallback(callback, callerName);
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
return internalInstance ? (internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ],
void enqueueUpdate(internalInstance)) : null;
},
enqueueCallbackInternal: function(internalInstance, callback) {
internalInstance._pendingCallbacks ? internalInstance._pendingCallbacks.push(callback) : internalInstance._pendingCallbacks = [ callback ],
enqueueUpdate(internalInstance);
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function(publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, "forceUpdate");
internalInstance && (internalInstance._pendingForceUpdate = !0, enqueueUpdate(internalInstance));
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function(publicInstance, completeState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, "replaceState");
internalInstance && (internalInstance._pendingStateQueue = [ completeState ], internalInstance._pendingReplaceState = !0,
enqueueUpdate(internalInstance));
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function(publicInstance, partialState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, "setState");
if (internalInstance) {
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState), enqueueUpdate(internalInstance);
}
},
enqueueElementInternal: function(internalInstance, newElement) {
internalInstance._pendingElement = newElement, enqueueUpdate(internalInstance);
},
validateCallback: function(callback, callerName) {
callback && "function" != typeof callback ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, formatUnexpectedArgument(callback)) : invariant(!1) : void 0;
}
};
module.exports = ReactUpdateQueue;
}).call(exports, __webpack_require__(17));
}, /* 123 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
"use strict";
var emptyObject = {};
"production" !== process.env.NODE_ENV && Object.freeze(emptyObject), module.exports = emptyObject;
}).call(exports, __webpack_require__(17));
}, /* 124 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shouldUpdateReactComponent
*/
"use strict";
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = null === prevElement || prevElement === !1, nextEmpty = null === nextElement || nextElement === !1;
if (prevEmpty || nextEmpty) return prevEmpty === nextEmpty;
var prevType = typeof prevElement, nextType = typeof nextElement;
return "string" === prevType || "number" === prevType ? "string" === nextType || "number" === nextType : "object" === nextType && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
module.exports = shouldUpdateReactComponent;
}, /* 125 */
/***/
function(module, exports) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponent
*/
"use strict";
var emptyComponentFactory, ReactEmptyComponentInjection = {
injectEmptyComponentFactory: function(factory) {
emptyComponentFactory = factory;
}
}, ReactEmptyComponent = {
create: function(instantiate) {
return emptyComponentFactory(instantiate);
}
};
ReactEmptyComponent.injection = ReactEmptyComponentInjection, module.exports = ReactEmptyComponent;
}, /* 126 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeComponent
*/
"use strict";
/**
* Get a composite component wrapper class for a specific tag.
*
* @param {ReactElement} element The tag for which to get the class.
* @return {function} The React class constructor function.
*/
function getComponentClassForElement(element) {
if ("function" == typeof element.type) return element.type;
var tag = element.type, componentClass = tagToComponentClass[tag];
return null == componentClass && (tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag)),
componentClass;
}
/**
* Get a native internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
return genericComponentClass ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "There is no registered component for the tag %s", element.type) : invariant(!1),
new genericComponentClass(element);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var _assign = __webpack_require__(30), invariant = __webpack_require__(18), autoGenerateWrapperClass = null, genericComponentClass = null, tagToComponentClass = {}, textComponentClass = null, ReactNativeComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function(componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function(componentClass) {
textComponentClass = componentClass;
},
// This accepts a keyed object with classes as values. Each key represents a
// tag. That particular tag will use this class instead of the generic one.
injectComponentClasses: function(componentClasses) {
_assign(tagToComponentClass, componentClasses);
}
}, ReactNativeComponent = {
getComponentClassForElement: getComponentClassForElement,
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactNativeComponentInjection
};
module.exports = ReactNativeComponent;
}).call(exports, __webpack_require__(17));
}, /* 127 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule flattenChildren
*/
"use strict";
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext, keyUnique = void 0 === result[name];
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(keyUnique, "flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.", KeyEscapeUtils.unescape(name)) : void 0),
keyUnique && null != child && (result[name] = child);
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (null == children) return children;
var result = {};
return traverseAllChildren(children, flattenSingleChildIntoContext, result), result;
}
var KeyEscapeUtils = __webpack_require__(112), traverseAllChildren = __webpack_require__(111), warning = __webpack_require__(24);
module.exports = flattenChildren;
}).call(exports, __webpack_require__(17));
}, /* 128 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerRenderingTransaction
*/
"use strict";
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction(), this.renderToStaticMarkup = renderToStaticMarkup,
this.useCreateElement = !1;
}
var _assign = __webpack_require__(30), PooledClass = __webpack_require__(31), Transaction = __webpack_require__(54), TRANSACTION_WRAPPERS = [], noopCallbackQueue = {
enqueue: function() {}
}, Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap procedures.
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function() {
return noopCallbackQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function() {},
checkpoint: function() {},
rollback: function() {}
};
_assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin), PooledClass.addPoolingTo(ReactServerRenderingTransaction),
module.exports = ReactServerRenderingTransaction;
}, /* 129 */
/***/
function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*
*/
/*eslint-disable no-self-compare */
"use strict";
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
// SameValue algorithm
return x === y ? 0 !== x || 1 / x === 1 / y : x !== x && y !== y;
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (is(objA, objB)) return !0;
if ("object" != typeof objA || null === objA || "object" != typeof objB || null === objB) return !1;
var keysA = Object.keys(objA), keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return !1;
// Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) return !1;
return !0;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
module.exports = shallowEqual;
}, /* 130 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule validateDOMNesting
*/
"use strict";
var _assign = __webpack_require__(30), emptyFunction = __webpack_require__(25), warning = __webpack_require__(24), validateDOMNesting = emptyFunction;
if ("production" !== process.env.NODE_ENV) {
// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags = [ "address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "menu", "menuitem", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp" ], inScopeTags = [ "applet", "caption", "html", "table", "td", "th", "marquee", "object", "template", // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
"foreignObject", "desc", "title" ], buttonScopeTags = inScopeTags.concat([ "button" ]), impliedEndTags = [ "dd", "dt", "li", "option", "optgroup", "p", "rp", "rt" ], emptyAncestorInfo = {
current: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
}, updatedAncestorInfo = function(oldInfo, tag, instance) {
var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo), info = {
tag: tag,
instance: instance
};
// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
return -1 !== inScopeTags.indexOf(tag) && (ancestorInfo.aTagInScope = null, ancestorInfo.buttonTagInScope = null,
ancestorInfo.nobrTagInScope = null), -1 !== buttonScopeTags.indexOf(tag) && (ancestorInfo.pTagInButtonScope = null),
-1 !== specialTags.indexOf(tag) && "address" !== tag && "div" !== tag && "p" !== tag && (ancestorInfo.listItemTagAutoclosing = null,
ancestorInfo.dlItemTagAutoclosing = null), ancestorInfo.current = info, "form" === tag && (ancestorInfo.formTag = info),
"a" === tag && (ancestorInfo.aTagInScope = info), "button" === tag && (ancestorInfo.buttonTagInScope = info),
"nobr" === tag && (ancestorInfo.nobrTagInScope = info), "p" === tag && (ancestorInfo.pTagInButtonScope = info),
"li" === tag && (ancestorInfo.listItemTagAutoclosing = info), "dd" !== tag && "dt" !== tag || (ancestorInfo.dlItemTagAutoclosing = info),
ancestorInfo;
}, isTagValidWithParent = function(tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case "select":
return "option" === tag || "optgroup" === tag || "#text" === tag;
case "optgroup":
return "option" === tag || "#text" === tag;
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case "option":
return "#text" === tag;
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case "tr":
return "th" === tag || "td" === tag || "style" === tag || "script" === tag || "template" === tag;
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case "tbody":
case "thead":
case "tfoot":
return "tr" === tag || "style" === tag || "script" === tag || "template" === tag;
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case "colgroup":
return "col" === tag || "template" === tag;
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case "table":
return "caption" === tag || "colgroup" === tag || "tbody" === tag || "tfoot" === tag || "thead" === tag || "style" === tag || "script" === tag || "template" === tag;
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case "head":
return "base" === tag || "basefont" === tag || "bgsound" === tag || "link" === tag || "meta" === tag || "title" === tag || "noscript" === tag || "noframes" === tag || "style" === tag || "script" === tag || "template" === tag;
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case "html":
return "head" === tag || "body" === tag;
case "#document":
return "html" === tag;
}
// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch (tag) {
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
return "h1" !== parentTag && "h2" !== parentTag && "h3" !== parentTag && "h4" !== parentTag && "h5" !== parentTag && "h6" !== parentTag;
case "rp":
case "rt":
return -1 === impliedEndTags.indexOf(parentTag);
case "body":
case "caption":
case "col":
case "colgroup":
case "frame":
case "head":
case "html":
case "tbody":
case "td":
case "tfoot":
case "th":
case "thead":
case "tr":
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return null == parentTag;
}
return !0;
}, findInvalidAncestorForTag = function(tag, ancestorInfo) {
switch (tag) {
case "address":
case "article":
case "aside":
case "blockquote":
case "center":
case "details":
case "dialog":
case "dir":
case "div":
case "dl":
case "fieldset":
case "figcaption":
case "figure":
case "footer":
case "header":
case "hgroup":
case "main":
case "menu":
case "nav":
case "ol":
case "p":
case "section":
case "summary":
case "ul":
case "pre":
case "listing":
case "table":
case "hr":
case "xmp":
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
return ancestorInfo.pTagInButtonScope;
case "form":
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case "li":
return ancestorInfo.listItemTagAutoclosing;
case "dd":
case "dt":
return ancestorInfo.dlItemTagAutoclosing;
case "button":
return ancestorInfo.buttonTagInScope;
case "a":
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case "nobr":
return ancestorInfo.nobrTagInScope;
}
return null;
}, findOwnerStack = function(instance) {
if (!instance) return [];
var stack = [];
do stack.push(instance); while (instance = instance._currentElement._owner);
return stack.reverse(), stack;
}, didWarn = {};
validateDOMNesting = function(childTag, childInstance, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current, parentTag = parentInfo && parentInfo.tag, invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo, invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo), problematic = invalidParent || invalidAncestor;
if (problematic) {
var i, ancestorTag = problematic.tag, ancestorInstance = problematic.instance, childOwner = childInstance && childInstance._currentElement._owner, ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner, childOwners = findOwnerStack(childOwner), ancestorOwners = findOwnerStack(ancestorOwner), minStackLen = Math.min(childOwners.length, ancestorOwners.length), deepestCommon = -1;
for (i = 0; minStackLen > i && childOwners[i] === ancestorOwners[i]; i++) deepestCommon = i;
var UNKNOWN = "(unknown)", childOwnerNames = childOwners.slice(deepestCommon + 1).map(function(inst) {
return inst.getName() || UNKNOWN;
}), ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function(inst) {
return inst.getName() || UNKNOWN;
}), ownerInfo = [].concat(-1 !== deepestCommon ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, invalidAncestor ? [ "..." ] : [], childOwnerNames, childTag).join(" > "), warnKey = !!invalidParent + "|" + childTag + "|" + ancestorTag + "|" + ownerInfo;
if (didWarn[warnKey]) return;
didWarn[warnKey] = !0;
var tagDisplayName = childTag;
if ("#text" !== childTag && (tagDisplayName = "<" + childTag + ">"), invalidParent) {
var info = "";
"table" === ancestorTag && "tr" === childTag && (info += " Add a <tbody> to your code to match the DOM tree generated by the browser."),
"production" !== process.env.NODE_ENV ? warning(!1, "validateDOMNesting(...): %s cannot appear as a child of <%s>. See %s.%s", tagDisplayName, ancestorTag, ownerInfo, info) : void 0;
} else "production" !== process.env.NODE_ENV ? warning(!1, "validateDOMNesting(...): %s cannot appear as a descendant of <%s>. See %s.", tagDisplayName, ancestorTag, ownerInfo) : void 0;
}
}, validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo, // For testing
validateDOMNesting.isTagValidInContext = function(tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current, parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
}).call(exports, __webpack_require__(17));
}, /* 131 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMEmptyComponent
*/
"use strict";
var _assign = __webpack_require__(30), DOMLazyTree = __webpack_require__(67), ReactDOMComponentTree = __webpack_require__(38), ReactDOMEmptyComponent = function(instantiate) {
// ReactCompositeComponent uses this:
this._currentElement = null, // ReactDOMComponentTree uses these:
this._nativeNode = null, this._nativeParent = null, this._nativeContainerInfo = null,
this._domID = null;
};
_assign(ReactDOMEmptyComponent.prototype, {
mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) {
var domID = nativeContainerInfo._idCounter++;
this._domID = domID, this._nativeParent = nativeParent, this._nativeContainerInfo = nativeContainerInfo;
var nodeValue = " react-empty: " + this._domID + " ";
if (transaction.useCreateElement) {
var ownerDocument = nativeContainerInfo._ownerDocument, node = ownerDocument.createComment(nodeValue);
return ReactDOMComponentTree.precacheNode(this, node), DOMLazyTree(node);
}
return transaction.renderToStaticMarkup ? "" : "<!--" + nodeValue + "-->";
},
receiveComponent: function() {},
getNativeNode: function() {
return ReactDOMComponentTree.getNodeFromInstance(this);
},
unmountComponent: function() {
ReactDOMComponentTree.uncacheNode(this);
}
}), module.exports = ReactDOMEmptyComponent;
}, /* 132 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTreeTraversal
*/
"use strict";
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA, instB) {
"_nativeNode" in instA ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "getNodeFromInstance: Invalid argument.") : invariant(!1),
"_nativeNode" in instB ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "getNodeFromInstance: Invalid argument.") : invariant(!1);
for (var depthA = 0, tempA = instA; tempA; tempA = tempA._nativeParent) depthA++;
for (var depthB = 0, tempB = instB; tempB; tempB = tempB._nativeParent) depthB++;
// If A is deeper, crawl up.
for (;depthA - depthB > 0; ) instA = instA._nativeParent, depthA--;
// If B is deeper, crawl up.
for (;depthB - depthA > 0; ) instB = instB._nativeParent, depthB--;
for (// Walk in lockstep until we find a match.
var depth = depthA; depth--; ) {
if (instA === instB) return instA;
instA = instA._nativeParent, instB = instB._nativeParent;
}
return null;
}
/**
* Return if A is an ancestor of B.
*/
function isAncestor(instA, instB) {
"_nativeNode" in instA ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "isAncestor: Invalid argument.") : invariant(!1),
"_nativeNode" in instB ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "isAncestor: Invalid argument.") : invariant(!1);
for (;instB; ) {
if (instB === instA) return !0;
instB = instB._nativeParent;
}
return !1;
}
/**
* Return the parent instance of the passed-in instance.
*/
function getParentInstance(inst) {
return "_nativeNode" in inst ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "getParentInstance: Invalid argument.") : invariant(!1),
inst._nativeParent;
}
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*/
function traverseTwoPhase(inst, fn, arg) {
for (var path = []; inst; ) path.push(inst), inst = inst._nativeParent;
var i;
for (i = path.length; i-- > 0; ) fn(path[i], !1, arg);
for (i = 0; i < path.length; i++) fn(path[i], !0, arg);
}
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* Does not invoke the callback on the nearest common ancestor because nothing
* "entered" or "left" that element.
*/
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
for (var common = from && to ? getLowestCommonAncestor(from, to) : null, pathFrom = []; from && from !== common; ) pathFrom.push(from),
from = from._nativeParent;
for (var pathTo = []; to && to !== common; ) pathTo.push(to), to = to._nativeParent;
var i;
for (i = 0; i < pathFrom.length; i++) fn(pathFrom[i], !0, argFrom);
for (i = pathTo.length; i-- > 0; ) fn(pathTo[i], !1, argTo);
}
var invariant = __webpack_require__(18);
module.exports = {
isAncestor: isAncestor,
getLowestCommonAncestor: getLowestCommonAncestor,
getParentInstance: getParentInstance,
traverseTwoPhase: traverseTwoPhase,
traverseEnterLeave: traverseEnterLeave
};
}).call(exports, __webpack_require__(17));
}, /* 133 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextComponent
*/
"use strict";
var _assign = __webpack_require__(30), DOMChildrenOperations = __webpack_require__(66), DOMLazyTree = __webpack_require__(67), ReactDOMComponentTree = __webpack_require__(38), ReactInstrumentation = __webpack_require__(44), escapeTextContentForBrowser = __webpack_require__(71), invariant = __webpack_require__(18), validateDOMNesting = __webpack_require__(130), ReactDOMTextComponent = function(text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text, this._stringText = "" + text, // ReactDOMComponentTree uses these:
this._nativeNode = null, this._nativeParent = null, // Properties
this._domID = null, this._mountIndex = 0, this._closingComment = null, this._commentNodes = null;
};
_assign(ReactDOMTextComponent.prototype, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(transaction, nativeParent, nativeContainerInfo, context) {
if ("production" !== process.env.NODE_ENV) {
ReactInstrumentation.debugTool.onSetText(this._debugID, this._stringText);
var parentInfo;
null != nativeParent ? parentInfo = nativeParent._ancestorInfo : null != nativeContainerInfo && (parentInfo = nativeContainerInfo._ancestorInfo),
parentInfo && // parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting("#text", this, parentInfo);
}
var domID = nativeContainerInfo._idCounter++, openingValue = " react-text: " + domID + " ", closingValue = " /react-text ";
if (this._domID = domID, this._nativeParent = nativeParent, transaction.useCreateElement) {
var ownerDocument = nativeContainerInfo._ownerDocument, openingComment = ownerDocument.createComment(openingValue), closingComment = ownerDocument.createComment(closingValue), lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment());
return DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)), this._stringText && DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))),
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)), ReactDOMComponentTree.precacheNode(this, openingComment),
this._closingComment = closingComment, lazyTree;
}
var escapedText = escapeTextContentForBrowser(this._stringText);
return transaction.renderToStaticMarkup ? escapedText : "<!--" + openingValue + "-->" + escapedText + "<!--" + closingValue + "-->";
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = "" + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var commentNodes = this.getNativeNode();
DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText),
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onSetText(this._debugID, nextStringText);
}
}
},
getNativeNode: function() {
var nativeNode = this._commentNodes;
if (nativeNode) return nativeNode;
if (!this._closingComment) for (var openingComment = ReactDOMComponentTree.getNodeFromInstance(this), node = openingComment.nextSibling; ;) {
if (null == node ? "production" !== process.env.NODE_ENV ? invariant(!1, "Missing closing comment for text component %s", this._domID) : invariant(!1) : void 0,
8 === node.nodeType && " /react-text " === node.nodeValue) {
this._closingComment = node;
break;
}
node = node.nextSibling;
}
return nativeNode = [ this._nativeNode, this._closingComment ], this._commentNodes = nativeNode,
nativeNode;
},
unmountComponent: function() {
this._closingComment = null, this._commentNodes = null, ReactDOMComponentTree.uncacheNode(this);
}
}), module.exports = ReactDOMTextComponent;
}).call(exports, __webpack_require__(17));
}, /* 134 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultBatchingStrategy
*/
"use strict";
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
var _assign = __webpack_require__(30), ReactUpdates = __webpack_require__(41), Transaction = __webpack_require__(54), emptyFunction = __webpack_require__(25), RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function() {
ReactDefaultBatchingStrategy.isBatchingUpdates = !1;
}
}, FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
}, TRANSACTION_WRAPPERS = [ FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES ];
_assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction(), ReactDefaultBatchingStrategy = {
isBatchingUpdates: !1,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function(callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = !0, // The code is written this way to avoid extra allocations
alreadyBatchingUpdates ? callback(a, b, c, d, e) : transaction.perform(callback, null, a, b, c, d, e);
}
};
module.exports = ReactDefaultBatchingStrategy;
}, /* 135 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventListener
*/
"use strict";
/**
* Find the deepest React component completely containing the root of the
* passed-in instance (for use when entire React trees are nested within each
* other). If React trees are not nested, returns null.
*/
function findParent(inst) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
for (;inst._nativeParent; ) inst = inst._nativeParent;
var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst), container = rootNode.parentNode;
return ReactDOMComponentTree.getClosestInstanceFromNode(container);
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType, this.nativeEvent = nativeEvent, this.ancestors = [];
}
function handleTopLevelImpl(bookKeeping) {
var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent), targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget), ancestor = targetInst;
do bookKeeping.ancestors.push(ancestor), ancestor = ancestor && findParent(ancestor); while (ancestor);
for (var i = 0; i < bookKeeping.ancestors.length; i++) targetInst = bookKeeping.ancestors[i],
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var _assign = __webpack_require__(30), EventListener = __webpack_require__(136), ExecutionEnvironment = __webpack_require__(28), PooledClass = __webpack_require__(31), ReactDOMComponentTree = __webpack_require__(38), ReactUpdates = __webpack_require__(41), getEventTarget = __webpack_require__(55), getUnboundedScrollPosition = __webpack_require__(137);
_assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function() {
this.topLevelType = null, this.nativeEvent = null, this.ancestors.length = 0;
}
}), PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
var ReactEventListener = {
_enabled: !0,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function(handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function(enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function() {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function(topLevelType, handlerBaseName, handle) {
var element = handle;
return element ? EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)) : null;
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function(topLevelType, handlerBaseName, handle) {
var element = handle;
return element ? EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)) : null;
},
monitorScrollValue: function(refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, "scroll", callback);
},
dispatchEvent: function(topLevelType, nativeEvent) {
if (ReactEventListener._enabled) {
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
}
};
module.exports = ReactEventListener;
}, /* 136 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @typechecks
*/
var emptyFunction = __webpack_require__(25), EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function(target, eventType, callback) {
return target.addEventListener ? (target.addEventListener(eventType, callback, !1),
{
remove: function() {
target.removeEventListener(eventType, callback, !1);
}
}) : target.attachEvent ? (target.attachEvent("on" + eventType, callback), {
remove: function() {
target.detachEvent("on" + eventType, callback);
}
}) : void 0;
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function(target, eventType, callback) {
return target.addEventListener ? (target.addEventListener(eventType, callback, !0),
{
remove: function() {
target.removeEventListener(eventType, callback, !0);
}
}) : ("production" !== process.env.NODE_ENV && console.error("Attempted to listen to events during the capture phase on a browser that does not support the capture phase. Your application will not receive some events."),
{
remove: emptyFunction
});
},
registerDefault: function() {}
};
module.exports = EventListener;
}).call(exports, __webpack_require__(17));
}, /* 137 */
/***/
function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
"use strict";
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
return scrollable === window ? {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
} : {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
}, /* 138 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInjection
*/
"use strict";
var DOMProperty = __webpack_require__(39), EventPluginHub = __webpack_require__(20), EventPluginUtils = __webpack_require__(22), ReactComponentEnvironment = __webpack_require__(116), ReactClass = __webpack_require__(139), ReactEmptyComponent = __webpack_require__(125), ReactBrowserEventEmitter = __webpack_require__(95), ReactNativeComponent = __webpack_require__(126), ReactUpdates = __webpack_require__(41), ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventPluginUtils: EventPluginUtils.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
}, /* 139 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactClass
*/
"use strict";
// noop
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) typeDef.hasOwnProperty(propName) && ("production" !== process.env.NODE_ENV ? warning("function" == typeof typeDef[propName], "%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.", Constructor.displayName || "ReactClass", ReactPropTypeLocationNames[location], propName) : void 0);
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
ReactClassMixin.hasOwnProperty(name) && (specPolicy !== SpecPolicy.OVERRIDE_BASE ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.", name) : invariant(!1) : void 0),
// Disallow defining methods more than once unless explicitly allowed.
isAlreadyDefined && (specPolicy !== SpecPolicy.DEFINE_MANY && specPolicy !== SpecPolicy.DEFINE_MANY_MERGED ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.", name) : invariant(!1) : void 0);
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (spec) {
"function" == typeof spec ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: You're attempting to use a component class or function as a mixin. Instead, just use a regular object.") : invariant(!1) : void 0,
ReactElement.isValidElement(spec) ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object.") : invariant(!1) : void 0;
var proto = Constructor.prototype, autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
spec.hasOwnProperty(MIXINS_KEY) && RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
for (var name in spec) if (spec.hasOwnProperty(name) && name !== MIXINS_KEY) {
var property = spec[name], isAlreadyDefined = proto.hasOwnProperty(name);
if (validateMethodOverride(isAlreadyDefined, name), RESERVED_SPEC_KEYS.hasOwnProperty(name)) RESERVED_SPEC_KEYS[name](Constructor, property); else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name), isFunction = "function" == typeof property, shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== !1;
if (shouldAutoBind) autoBindPairs.push(name, property), proto[name] = property; else if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
!isReactClassMethod || specPolicy !== SpecPolicy.DEFINE_MANY_MERGED && specPolicy !== SpecPolicy.DEFINE_MANY ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.", specPolicy, name) : invariant(!1) : void 0,
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ? proto[name] = createMergedResultFunction(proto[name], property) : specPolicy === SpecPolicy.DEFINE_MANY && (proto[name] = createChainedFunction(proto[name], property));
} else proto[name] = property, "production" !== process.env.NODE_ENV && "function" == typeof property && spec.displayName && (proto[name].displayName = spec.displayName + "_" + name);
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (statics) for (var name in statics) {
var property = statics[name];
if (statics.hasOwnProperty(name)) {
var isReserved = name in RESERVED_SPEC_KEYS;
isReserved ? "production" !== process.env.NODE_ENV ? invariant(!1, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : invariant(!1) : void 0;
var isInherited = name in Constructor;
isInherited ? "production" !== process.env.NODE_ENV ? invariant(!1, "ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.", name) : invariant(!1) : void 0,
Constructor[name] = property;
}
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
one && two && "object" == typeof one && "object" == typeof two ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.") : invariant(!1);
for (var key in two) two.hasOwnProperty(key) && (void 0 !== one[key] ? "production" !== process.env.NODE_ENV ? invariant(!1, "mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.", key) : invariant(!1) : void 0,
one[key] = two[key]);
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function() {
var a = one.apply(this, arguments), b = two.apply(this, arguments);
if (null == a) return b;
if (null == b) return a;
var c = {};
return mergeIntoWithNoDuplicateKeys(c, a), mergeIntoWithNoDuplicateKeys(c, b), c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function() {
one.apply(this, arguments), two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if ("production" !== process.env.NODE_ENV) {
boundMethod.__reactBoundContext = component, boundMethod.__reactBoundMethod = method,
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName, _bind = boundMethod.bind;
boundMethod.bind = function(newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _len > _key; _key++) args[_key - 1] = arguments[_key];
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && null !== newThis) "production" !== process.env.NODE_ENV ? warning(!1, "bind(): React component methods may only be bound to the component instance. See %s", componentName) : void 0; else if (!args.length) return "production" !== process.env.NODE_ENV ? warning(!1, "bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See %s", componentName) : void 0,
boundMethod;
var reboundMethod = _bind.apply(boundMethod, arguments);
return reboundMethod.__reactBoundContext = component, reboundMethod.__reactBoundMethod = method,
reboundMethod.__reactBoundArguments = args, reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
for (var pairs = component.__reactAutoBindPairs, i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i], method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
var _assign = __webpack_require__(30), ReactComponent = __webpack_require__(140), ReactElement = __webpack_require__(103), ReactPropTypeLocations = __webpack_require__(108), ReactPropTypeLocationNames = __webpack_require__(106), ReactNoopUpdateQueue = __webpack_require__(141), emptyObject = __webpack_require__(123), invariant = __webpack_require__(18), keyMirror = __webpack_require__(16), keyOf = __webpack_require__(36), warning = __webpack_require__(24), MIXINS_KEY = keyOf({
mixins: null
}), SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
}), injectedMixins = [], ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
}, RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) for (var i = 0; i < mixins.length; i++) mixSpecIntoComponent(Constructor, mixins[i]);
},
childContextTypes: function(Constructor, childContextTypes) {
"production" !== process.env.NODE_ENV && validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext),
Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function(Constructor, contextTypes) {
"production" !== process.env.NODE_ENV && validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context),
Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function(Constructor, getDefaultProps) {
Constructor.getDefaultProps ? Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps) : Constructor.getDefaultProps = getDefaultProps;
},
propTypes: function(Constructor, propTypes) {
"production" !== process.env.NODE_ENV && validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop),
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function() {}
}, ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function(newState, callback) {
this.updater.enqueueReplaceState(this, newState), callback && this.updater.enqueueCallback(this, callback, "replaceState");
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return this.updater.isMounted(this);
}
}, ReactClassComponent = function() {};
_assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
/**
* Creates a composite component class given a class specification.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function(spec) {
var Constructor = function(props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(this instanceof Constructor, "Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory") : void 0),
// Wire up auto-binding
this.__reactAutoBindPairs.length && bindAutoBindMethods(this), this.props = props,
this.context = context, this.refs = emptyObject, this.updater = updater || ReactNoopUpdateQueue,
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
"production" !== process.env.NODE_ENV && void 0 === initialState && this.getInitialState._isMockFunction && (// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null), "object" != typeof initialState || Array.isArray(initialState) ? "production" !== process.env.NODE_ENV ? invariant(!1, "%s.getInitialState(): must return an object or null", Constructor.displayName || "ReactCompositeComponent") : invariant(!1) : void 0,
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent(), Constructor.prototype.constructor = Constructor,
Constructor.prototype.__reactAutoBindPairs = [], injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)),
mixSpecIntoComponent(Constructor, spec), // Initialize the defaultProps property after all mixins have been merged.
Constructor.getDefaultProps && (Constructor.defaultProps = Constructor.getDefaultProps()),
"production" !== process.env.NODE_ENV && (// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
Constructor.getDefaultProps && (Constructor.getDefaultProps.isReactClassApproved = {}),
Constructor.prototype.getInitialState && (Constructor.prototype.getInitialState.isReactClassApproved = {})),
Constructor.prototype.render ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "createClass(...): Class specification must implement a `render` method.") : invariant(!1),
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!Constructor.prototype.componentShouldUpdate, "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", spec.displayName || "A component") : void 0,
"production" !== process.env.NODE_ENV ? warning(!Constructor.prototype.componentWillRecieveProps, "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", spec.displayName || "A component") : void 0);
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) Constructor.prototype[methodName] || (Constructor.prototype[methodName] = null);
return Constructor;
},
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactClass;
}).call(exports, __webpack_require__(17));
}, /* 140 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponent
*/
"use strict";
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context, updater) {
this.props = props, this.context = context, this.refs = emptyObject, // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
var ReactNoopUpdateQueue = __webpack_require__(141), ReactInstrumentation = __webpack_require__(44), canDefineProperty = __webpack_require__(105), emptyObject = __webpack_require__(123), invariant = __webpack_require__(18), warning = __webpack_require__(24);
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if (ReactComponent.prototype.isReactComponent = {}, /**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function(partialState, callback) {
"object" != typeof partialState && "function" != typeof partialState && null != partialState ? "production" !== process.env.NODE_ENV ? invariant(!1, "setState(...): takes an object of state variables to update or a function which returns an object of state variables.") : invariant(!1) : void 0,
"production" !== process.env.NODE_ENV && (ReactInstrumentation.debugTool.onSetState(),
"production" !== process.env.NODE_ENV ? warning(null != partialState, "setState(...): You passed an undefined or null state object; instead, use forceUpdate().") : void 0),
this.updater.enqueueSetState(this, partialState), callback && this.updater.enqueueCallback(this, callback, "setState");
}, /**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function(callback) {
this.updater.enqueueForceUpdate(this), callback && this.updater.enqueueCallback(this, callback, "forceUpdate");
}, "production" !== process.env.NODE_ENV) {
var deprecatedAPIs = {
isMounted: [ "isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks." ],
replaceState: [ "replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)." ]
}, defineDeprecationWarning = function(methodName, info) {
canDefineProperty && Object.defineProperty(ReactComponent.prototype, methodName, {
get: function() {
"production" !== process.env.NODE_ENV ? warning(!1, "%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]) : void 0;
}
});
};
for (var fnName in deprecatedAPIs) deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
module.exports = ReactComponent;
}).call(exports, __webpack_require__(17));
}, /* 141 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNoopUpdateQueue
*/
"use strict";
function warnTDZ(publicInstance, callerName) {
"production" !== process.env.NODE_ENV && ("production" !== process.env.NODE_ENV ? warning(!1, "%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.", callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || "") : void 0);
}
var warning = __webpack_require__(24), ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function(publicInstance) {
return !1;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function(publicInstance, callback) {},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function(publicInstance) {
warnTDZ(publicInstance, "forceUpdate");
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function(publicInstance, completeState) {
warnTDZ(publicInstance, "replaceState");
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function(publicInstance, partialState) {
warnTDZ(publicInstance, "setState");
}
};
module.exports = ReactNoopUpdateQueue;
}).call(exports, __webpack_require__(17));
}, /* 142 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconcileTransaction
*/
"use strict";
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction(useCreateElement) {
this.reinitializeTransaction(), // Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = !1, this.reactMountReady = CallbackQueue.getPooled(null),
this.useCreateElement = useCreateElement;
}
var _assign = __webpack_require__(30), CallbackQueue = __webpack_require__(42), PooledClass = __webpack_require__(31), ReactBrowserEventEmitter = __webpack_require__(95), ReactInputSelection = __webpack_require__(143), Transaction = __webpack_require__(54), SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
}, EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function() {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
return ReactBrowserEventEmitter.setEnabled(!1), currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
* restores the previous value.
*/
close: function(previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
}, ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function() {
this.reactMountReady.notifyAll();
}
}, TRANSACTION_WRAPPERS = [ SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING ], Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function() {
return this.reactMountReady;
},
/**
* Save current transaction state -- if the return value from this method is
* passed to `rollback`, the transaction will be reset to that state.
*/
checkpoint: function() {
// reactMountReady is the our only stateful wrapper
return this.reactMountReady.checkpoint();
},
rollback: function(checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function() {
CallbackQueue.release(this.reactMountReady), this.reactMountReady = null;
}
};
_assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin), PooledClass.addPoolingTo(ReactReconcileTransaction),
module.exports = ReactReconcileTransaction;
}, /* 143 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInputSelection
*/
"use strict";
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
var ReactDOMSelection = __webpack_require__(144), containsNode = __webpack_require__(146), focusNode = __webpack_require__(81), getActiveElement = __webpack_require__(149), ReactInputSelection = {
hasSelectionCapabilities: function(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && ("input" === nodeName && "text" === elem.type || "textarea" === nodeName || "true" === elem.contentEditable);
},
getSelectionInformation: function() {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function(priorSelectionInformation) {
var curFocusedElem = getActiveElement(), priorFocusedElem = priorSelectionInformation.focusedElem, priorSelectionRange = priorSelectionInformation.selectionRange;
curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem) && (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem) && ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange),
focusNode(priorFocusedElem));
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function(input) {
var selection;
if ("selectionStart" in input) // Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
}; else if (document.selection && input.nodeName && "input" === input.nodeName.toLowerCase()) {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
range.parentElement() === input && (selection = {
start: -range.moveStart("character", -input.value.length),
end: -range.moveEnd("character", -input.value.length)
});
} else // Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
return selection || {
start: 0,
end: 0
};
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function(input, offsets) {
var start = offsets.start, end = offsets.end;
if (void 0 === end && (end = start), "selectionStart" in input) input.selectionStart = start,
input.selectionEnd = Math.min(end, input.value.length); else if (document.selection && input.nodeName && "input" === input.nodeName.toLowerCase()) {
var range = input.createTextRange();
range.collapse(!0), range.moveStart("character", start), range.moveEnd("character", end - start),
range.select();
} else ReactDOMSelection.setOffsets(input, offsets);
}
};
module.exports = ReactInputSelection;
}, /* 144 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelection
*/
"use strict";
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection, selectedRange = selection.createRange(), selectedLength = selectedRange.text.length, fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node), fromStart.setEndPoint("EndToStart", selectedRange);
var startOffset = fromStart.text.length, endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || 0 === selection.rangeCount) return null;
var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset, currentRange = selection.getRangeAt(0);
// In Firefox, range.startContainer and range.endContainer can be "anonymous
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
// divs do not seem to expose properties, triggering a "Permission denied
// error" if any of its properties are accessed. The only seemingly possible
// way to avoid erroring is to access a property that typically works for
// non-anonymous divs and catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
currentRange.startContainer.nodeType, currentRange.endContainer.nodeType;
} catch (e) {
return null;
}
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset), rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length, tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node), tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset), start = isTempRangeCollapsed ? 0 : tempRange.toString().length, end = start + rangeLength, detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset), detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var start, end, range = document.selection.createRange().duplicate();
void 0 === offsets.end ? (start = offsets.start, end = start) : offsets.start > offsets.end ? (start = offsets.end,
end = offsets.start) : (start = offsets.start, end = offsets.end), range.moveToElementText(node),
range.moveStart("character", start), range.setEndPoint("EndToStart", range), range.moveEnd("character", end - start),
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programmatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (window.getSelection) {
var selection = window.getSelection(), length = node[getTextContentAccessor()].length, start = Math.min(offsets.start, length), end = void 0 === offsets.end ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start, start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start), endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset), selection.removeAllRanges(),
start > end ? (selection.addRange(range), selection.extend(endMarker.node, endMarker.offset)) : (range.setEnd(endMarker.node, endMarker.offset),
selection.addRange(range));
}
}
}
var ExecutionEnvironment = __webpack_require__(28), getNodeForCharacterOffset = __webpack_require__(145), getTextContentAccessor = __webpack_require__(32), useIEOffsets = ExecutionEnvironment.canUseDOM && "selection" in document && !("getSelection" in window), ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
}, /* 145 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getNodeForCharacterOffset
*/
"use strict";
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
for (;node && node.firstChild; ) node = node.firstChild;
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
for (;node; ) {
if (node.nextSibling) return node.nextSibling;
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
for (var node = getLeafNode(root), nodeStart = 0, nodeEnd = 0; node; ) {
if (3 === node.nodeType) {
if (nodeEnd = nodeStart + node.textContent.length, offset >= nodeStart && nodeEnd >= offset) return {
node: node,
offset: offset - nodeStart
};
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
}, /* 146 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*/
function containsNode(outerNode, innerNode) {
return outerNode && innerNode ? outerNode === innerNode ? !0 : isTextNode(outerNode) ? !1 : isTextNode(innerNode) ? containsNode(outerNode, innerNode.parentNode) : "contains" in outerNode ? outerNode.contains(innerNode) : outerNode.compareDocumentPosition ? !!(16 & outerNode.compareDocumentPosition(innerNode)) : !1 : !1;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var isTextNode = __webpack_require__(147);
module.exports = containsNode;
}, /* 147 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && 3 == object.nodeType;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var isNode = __webpack_require__(148);
module.exports = isTextNode;
}, /* 148 */
/***/
function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
function isNode(object) {
return !(!object || !("function" == typeof Node ? object instanceof Node : "object" == typeof object && "number" == typeof object.nodeType && "string" == typeof object.nodeName));
}
module.exports = isNode;
}, /* 149 */
/***/
function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*/
function getActiveElement() {
if ("undefined" == typeof document) return null;
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
}, /* 150 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SVGDOMPropertyConfig
*/
"use strict";
var NS = {
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace"
}, ATTRS = {
accentHeight: "accent-height",
accumulate: 0,
additive: 0,
alignmentBaseline: "alignment-baseline",
allowReorder: "allowReorder",
alphabetic: 0,
amplitude: 0,
arabicForm: "arabic-form",
ascent: 0,
attributeName: "attributeName",
attributeType: "attributeType",
autoReverse: "autoReverse",
azimuth: 0,
baseFrequency: "baseFrequency",
baseProfile: "baseProfile",
baselineShift: "baseline-shift",
bbox: 0,
begin: 0,
bias: 0,
by: 0,
calcMode: "calcMode",
capHeight: "cap-height",
clip: 0,
clipPath: "clip-path",
clipRule: "clip-rule",
clipPathUnits: "clipPathUnits",
colorInterpolation: "color-interpolation",
colorInterpolationFilters: "color-interpolation-filters",
colorProfile: "color-profile",
colorRendering: "color-rendering",
contentScriptType: "contentScriptType",
contentStyleType: "contentStyleType",
cursor: 0,
cx: 0,
cy: 0,
d: 0,
decelerate: 0,
descent: 0,
diffuseConstant: "diffuseConstant",
direction: 0,
display: 0,
divisor: 0,
dominantBaseline: "dominant-baseline",
dur: 0,
dx: 0,
dy: 0,
edgeMode: "edgeMode",
elevation: 0,
enableBackground: "enable-background",
end: 0,
exponent: 0,
externalResourcesRequired: "externalResourcesRequired",
fill: 0,
fillOpacity: "fill-opacity",
fillRule: "fill-rule",
filter: 0,
filterRes: "filterRes",
filterUnits: "filterUnits",
floodColor: "flood-color",
floodOpacity: "flood-opacity",
focusable: 0,
fontFamily: "font-family",
fontSize: "font-size",
fontSizeAdjust: "font-size-adjust",
fontStretch: "font-stretch",
fontStyle: "font-style",
fontVariant: "font-variant",
fontWeight: "font-weight",
format: 0,
from: 0,
fx: 0,
fy: 0,
g1: 0,
g2: 0,
glyphName: "glyph-name",
glyphOrientationHorizontal: "glyph-orientation-horizontal",
glyphOrientationVertical: "glyph-orientation-vertical",
glyphRef: "glyphRef",
gradientTransform: "gradientTransform",
gradientUnits: "gradientUnits",
hanging: 0,
horizAdvX: "horiz-adv-x",
horizOriginX: "horiz-origin-x",
ideographic: 0,
imageRendering: "image-rendering",
"in": 0,
in2: 0,
intercept: 0,
k: 0,
k1: 0,
k2: 0,
k3: 0,
k4: 0,
kernelMatrix: "kernelMatrix",
kernelUnitLength: "kernelUnitLength",
kerning: 0,
keyPoints: "keyPoints",
keySplines: "keySplines",
keyTimes: "keyTimes",
lengthAdjust: "lengthAdjust",
letterSpacing: "letter-spacing",
lightingColor: "lighting-color",
limitingConeAngle: "limitingConeAngle",
local: 0,
markerEnd: "marker-end",
markerMid: "marker-mid",
markerStart: "marker-start",
markerHeight: "markerHeight",
markerUnits: "markerUnits",
markerWidth: "markerWidth",
mask: 0,
maskContentUnits: "maskContentUnits",
maskUnits: "maskUnits",
mathematical: 0,
mode: 0,
numOctaves: "numOctaves",
offset: 0,
opacity: 0,
operator: 0,
order: 0,
orient: 0,
orientation: 0,
origin: 0,
overflow: 0,
overlinePosition: "overline-position",
overlineThickness: "overline-thickness",
paintOrder: "paint-order",
panose1: "panose-1",
pathLength: "pathLength",
patternContentUnits: "patternContentUnits",
patternTransform: "patternTransform",
patternUnits: "patternUnits",
pointerEvents: "pointer-events",
points: 0,
pointsAtX: "pointsAtX",
pointsAtY: "pointsAtY",
pointsAtZ: "pointsAtZ",
preserveAlpha: "preserveAlpha",
preserveAspectRatio: "preserveAspectRatio",
primitiveUnits: "primitiveUnits",
r: 0,
radius: 0,
refX: "refX",
refY: "refY",
renderingIntent: "rendering-intent",
repeatCount: "repeatCount",
repeatDur: "repeatDur",
requiredExtensions: "requiredExtensions",
requiredFeatures: "requiredFeatures",
restart: 0,
result: 0,
rotate: 0,
rx: 0,
ry: 0,
scale: 0,
seed: 0,
shapeRendering: "shape-rendering",
slope: 0,
spacing: 0,
specularConstant: "specularConstant",
specularExponent: "specularExponent",
speed: 0,
spreadMethod: "spreadMethod",
startOffset: "startOffset",
stdDeviation: "stdDeviation",
stemh: 0,
stemv: 0,
stitchTiles: "stitchTiles",
stopColor: "stop-color",
stopOpacity: "stop-opacity",
strikethroughPosition: "strikethrough-position",
strikethroughThickness: "strikethrough-thickness",
string: 0,
stroke: 0,
strokeDasharray: "stroke-dasharray",
strokeDashoffset: "stroke-dashoffset",
strokeLinecap: "stroke-linecap",
strokeLinejoin: "stroke-linejoin",
strokeMiterlimit: "stroke-miterlimit",
strokeOpacity: "stroke-opacity",
strokeWidth: "stroke-width",
surfaceScale: "surfaceScale",
systemLanguage: "systemLanguage",
tableValues: "tableValues",
targetX: "targetX",
targetY: "targetY",
textAnchor: "text-anchor",
textDecoration: "text-decoration",
textRendering: "text-rendering",
textLength: "textLength",
to: 0,
transform: 0,
u1: 0,
u2: 0,
underlinePosition: "underline-position",
underlineThickness: "underline-thickness",
unicode: 0,
unicodeBidi: "unicode-bidi",
unicodeRange: "unicode-range",
unitsPerEm: "units-per-em",
vAlphabetic: "v-alphabetic",
vHanging: "v-hanging",
vIdeographic: "v-ideographic",
vMathematical: "v-mathematical",
values: 0,
vectorEffect: "vector-effect",
version: 0,
vertAdvY: "vert-adv-y",
vertOriginX: "vert-origin-x",
vertOriginY: "vert-origin-y",
viewBox: "viewBox",
viewTarget: "viewTarget",
visibility: 0,
widths: 0,
wordSpacing: "word-spacing",
writingMode: "writing-mode",
x: 0,
xHeight: "x-height",
x1: 0,
x2: 0,
xChannelSelector: "xChannelSelector",
xlinkActuate: "xlink:actuate",
xlinkArcrole: "xlink:arcrole",
xlinkHref: "xlink:href",
xlinkRole: "xlink:role",
xlinkShow: "xlink:show",
xlinkTitle: "xlink:title",
xlinkType: "xlink:type",
xmlBase: "xml:base",
xmlLang: "xml:lang",
xmlSpace: "xml:space",
y: 0,
y1: 0,
y2: 0,
yChannelSelector: "yChannelSelector",
z: 0,
zoomAndPan: "zoomAndPan"
}, SVGDOMPropertyConfig = {
Properties: {},
DOMAttributeNamespaces: {
xlinkActuate: NS.xlink,
xlinkArcrole: NS.xlink,
xlinkHref: NS.xlink,
xlinkRole: NS.xlink,
xlinkShow: NS.xlink,
xlinkTitle: NS.xlink,
xlinkType: NS.xlink,
xmlBase: NS.xml,
xmlLang: NS.xml,
xmlSpace: NS.xml
},
DOMAttributeNames: {}
};
Object.keys(ATTRS).forEach(function(key) {
SVGDOMPropertyConfig.Properties[key] = 0, ATTRS[key] && (SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]);
}), module.exports = SVGDOMPropertyConfig;
}, /* 151 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SelectEventPlugin
*/
"use strict";
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @return {object}
*/
function getSelection(node) {
if ("selectionStart" in node && ReactInputSelection.hasSelectionCapabilities(node)) return {
start: node.selectionStart,
end: node.selectionEnd
};
if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
}
if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown || null == activeElement || activeElement !== getActiveElement()) return null;
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget);
return syntheticEvent.type = "select", syntheticEvent.target = activeElement, EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent),
syntheticEvent;
}
return null;
}
var EventConstants = __webpack_require__(15), EventPropagators = __webpack_require__(19), ExecutionEnvironment = __webpack_require__(28), ReactDOMComponentTree = __webpack_require__(38), ReactInputSelection = __webpack_require__(143), SyntheticEvent = __webpack_require__(34), getActiveElement = __webpack_require__(149), isTextInputElement = __webpack_require__(57), keyOf = __webpack_require__(36), shallowEqual = __webpack_require__(129), topLevelTypes = EventConstants.topLevelTypes, skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && "documentMode" in document && document.documentMode <= 11, eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({
onSelect: null
}),
captured: keyOf({
onSelectCapture: null
})
},
dependencies: [ topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange ]
}
}, activeElement = null, activeElementInst = null, lastSelection = null, mouseDown = !1, hasListener = !1, ON_SELECT_KEY = keyOf({
onSelect: null
}), SelectEventPlugin = {
eventTypes: eventTypes,
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (!hasListener) return null;
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
(isTextInputElement(targetNode) || "true" === targetNode.contentEditable) && (activeElement = targetNode,
activeElementInst = targetInst, lastSelection = null);
break;
case topLevelTypes.topBlur:
activeElement = null, activeElementInst = null, lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = !0;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
return mouseDown = !1, constructSelectEvent(nativeEvent, nativeEventTarget);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case topLevelTypes.topSelectionChange:
if (skipSelectionChangeEvent) break;
// falls through
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent, nativeEventTarget);
}
return null;
},
didPutListener: function(inst, registrationName, listener) {
registrationName === ON_SELECT_KEY && (hasListener = !0);
}
};
module.exports = SelectEventPlugin;
}, /* 152 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SimpleEventPlugin
*/
"use strict";
var EventConstants = __webpack_require__(15), EventListener = __webpack_require__(136), EventPropagators = __webpack_require__(19), ReactDOMComponentTree = __webpack_require__(38), SyntheticAnimationEvent = __webpack_require__(153), SyntheticClipboardEvent = __webpack_require__(154), SyntheticEvent = __webpack_require__(34), SyntheticFocusEvent = __webpack_require__(155), SyntheticKeyboardEvent = __webpack_require__(156), SyntheticMouseEvent = __webpack_require__(60), SyntheticDragEvent = __webpack_require__(159), SyntheticTouchEvent = __webpack_require__(160), SyntheticTransitionEvent = __webpack_require__(161), SyntheticUIEvent = __webpack_require__(61), SyntheticWheelEvent = __webpack_require__(162), emptyFunction = __webpack_require__(25), getEventCharCode = __webpack_require__(157), invariant = __webpack_require__(18), keyOf = __webpack_require__(36), topLevelTypes = EventConstants.topLevelTypes, eventTypes = {
abort: {
phasedRegistrationNames: {
bubbled: keyOf({
onAbort: !0
}),
captured: keyOf({
onAbortCapture: !0
})
}
},
animationEnd: {
phasedRegistrationNames: {
bubbled: keyOf({
onAnimationEnd: !0
}),
captured: keyOf({
onAnimationEndCapture: !0
})
}
},
animationIteration: {
phasedRegistrationNames: {
bubbled: keyOf({
onAnimationIteration: !0
}),
captured: keyOf({
onAnimationIterationCapture: !0
})
}
},
animationStart: {
phasedRegistrationNames: {
bubbled: keyOf({
onAnimationStart: !0
}),
captured: keyOf({
onAnimationStartCapture: !0
})
}
},
blur: {
phasedRegistrationNames: {
bubbled: keyOf({
onBlur: !0
}),
captured: keyOf({
onBlurCapture: !0
})
}
},
canPlay: {
phasedRegistrationNames: {
bubbled: keyOf({
onCanPlay: !0
}),
captured: keyOf({
onCanPlayCapture: !0
})
}
},
canPlayThrough: {
phasedRegistrationNames: {
bubbled: keyOf({
onCanPlayThrough: !0
}),
captured: keyOf({
onCanPlayThroughCapture: !0
})
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({
onClick: !0
}),
captured: keyOf({
onClickCapture: !0
})
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({
onContextMenu: !0
}),
captured: keyOf({
onContextMenuCapture: !0
})
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({
onCopy: !0
}),
captured: keyOf({
onCopyCapture: !0
})
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({
onCut: !0
}),
captured: keyOf({
onCutCapture: !0
})
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({
onDoubleClick: !0
}),
captured: keyOf({
onDoubleClickCapture: !0
})
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({
onDrag: !0
}),
captured: keyOf({
onDragCapture: !0
})
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({
onDragEnd: !0
}),
captured: keyOf({
onDragEndCapture: !0
})
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({
onDragEnter: !0
}),
captured: keyOf({
onDragEnterCapture: !0
})
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({
onDragExit: !0
}),
captured: keyOf({
onDragExitCapture: !0
})
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({
onDragLeave: !0
}),
captured: keyOf({
onDragLeaveCapture: !0
})
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({
onDragOver: !0
}),
captured: keyOf({
onDragOverCapture: !0
})
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({
onDragStart: !0
}),
captured: keyOf({
onDragStartCapture: !0
})
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({
onDrop: !0
}),
captured: keyOf({
onDropCapture: !0
})
}
},
durationChange: {
phasedRegistrationNames: {
bubbled: keyOf({
onDurationChange: !0
}),
captured: keyOf({
onDurationChangeCapture: !0
})
}
},
emptied: {
phasedRegistrationNames: {
bubbled: keyOf({
onEmptied: !0
}),
captured: keyOf({
onEmptiedCapture: !0
})
}
},
encrypted: {
phasedRegistrationNames: {
bubbled: keyOf({
onEncrypted: !0
}),
captured: keyOf({
onEncryptedCapture: !0
})
}
},
ended: {
phasedRegistrationNames: {
bubbled: keyOf({
onEnded: !0
}),
captured: keyOf({
onEndedCapture: !0
})
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({
onError: !0
}),
captured: keyOf({
onErrorCapture: !0
})
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({
onFocus: !0
}),
captured: keyOf({
onFocusCapture: !0
})
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({
onInput: !0
}),
captured: keyOf({
onInputCapture: !0
})
}
},
invalid: {
phasedRegistrationNames: {
bubbled: keyOf({
onInvalid: !0
}),
captured: keyOf({
onInvalidCapture: !0
})
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({
onKeyDown: !0
}),
captured: keyOf({
onKeyDownCapture: !0
})
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({
onKeyPress: !0
}),
captured: keyOf({
onKeyPressCapture: !0
})
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({
onKeyUp: !0
}),
captured: keyOf({
onKeyUpCapture: !0
})
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({
onLoad: !0
}),
captured: keyOf({
onLoadCapture: !0
})
}
},
loadedData: {
phasedRegistrationNames: {
bubbled: keyOf({
onLoadedData: !0
}),
captured: keyOf({
onLoadedDataCapture: !0
})
}
},
loadedMetadata: {
phasedRegistrationNames: {
bubbled: keyOf({
onLoadedMetadata: !0
}),
captured: keyOf({
onLoadedMetadataCapture: !0
})
}
},
loadStart: {
phasedRegistrationNames: {
bubbled: keyOf({
onLoadStart: !0
}),
captured: keyOf({
onLoadStartCapture: !0
})
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({
onMouseDown: !0
}),
captured: keyOf({
onMouseDownCapture: !0
})
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({
onMouseMove: !0
}),
captured: keyOf({
onMouseMoveCapture: !0
})
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({
onMouseOut: !0
}),
captured: keyOf({
onMouseOutCapture: !0
})
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({
onMouseOver: !0
}),
captured: keyOf({
onMouseOverCapture: !0
})
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({
onMouseUp: !0
}),
captured: keyOf({
onMouseUpCapture: !0
})
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({
onPaste: !0
}),
captured: keyOf({
onPasteCapture: !0
})
}
},
pause: {
phasedRegistrationNames: {
bubbled: keyOf({
onPause: !0
}),
captured: keyOf({
onPauseCapture: !0
})
}
},
play: {
phasedRegistrationNames: {
bubbled: keyOf({
onPlay: !0
}),
captured: keyOf({
onPlayCapture: !0
})
}
},
playing: {
phasedRegistrationNames: {
bubbled: keyOf({
onPlaying: !0
}),
captured: keyOf({
onPlayingCapture: !0
})
}
},
progress: {
phasedRegistrationNames: {
bubbled: keyOf({
onProgress: !0
}),
captured: keyOf({
onProgressCapture: !0
})
}
},
rateChange: {
phasedRegistrationNames: {
bubbled: keyOf({
onRateChange: !0
}),
captured: keyOf({
onRateChangeCapture: !0
})
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({
onReset: !0
}),
captured: keyOf({
onResetCapture: !0
})
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({
onScroll: !0
}),
captured: keyOf({
onScrollCapture: !0
})
}
},
seeked: {
phasedRegistrationNames: {
bubbled: keyOf({
onSeeked: !0
}),
captured: keyOf({
onSeekedCapture: !0
})
}
},
seeking: {
phasedRegistrationNames: {
bubbled: keyOf({
onSeeking: !0
}),
captured: keyOf({
onSeekingCapture: !0
})
}
},
stalled: {
phasedRegistrationNames: {
bubbled: keyOf({
onStalled: !0
}),
captured: keyOf({
onStalledCapture: !0
})
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({
onSubmit: !0
}),
captured: keyOf({
onSubmitCapture: !0
})
}
},
suspend: {
phasedRegistrationNames: {
bubbled: keyOf({
onSuspend: !0
}),
captured: keyOf({
onSuspendCapture: !0
})
}
},
timeUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({
onTimeUpdate: !0
}),
captured: keyOf({
onTimeUpdateCapture: !0
})
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({
onTouchCancel: !0
}),
captured: keyOf({
onTouchCancelCapture: !0
})
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({
onTouchEnd: !0
}),
captured: keyOf({
onTouchEndCapture: !0
})
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({
onTouchMove: !0
}),
captured: keyOf({
onTouchMoveCapture: !0
})
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({
onTouchStart: !0
}),
captured: keyOf({
onTouchStartCapture: !0
})
}
},
transitionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({
onTransitionEnd: !0
}),
captured: keyOf({
onTransitionEndCapture: !0
})
}
},
volumeChange: {
phasedRegistrationNames: {
bubbled: keyOf({
onVolumeChange: !0
}),
captured: keyOf({
onVolumeChangeCapture: !0
})
}
},
waiting: {
phasedRegistrationNames: {
bubbled: keyOf({
onWaiting: !0
}),
captured: keyOf({
onWaitingCapture: !0
})
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({
onWheel: !0
}),
captured: keyOf({
onWheelCapture: !0
})
}
}
}, topLevelEventsToDispatchConfig = {
topAbort: eventTypes.abort,
topAnimationEnd: eventTypes.animationEnd,
topAnimationIteration: eventTypes.animationIteration,
topAnimationStart: eventTypes.animationStart,
topBlur: eventTypes.blur,
topCanPlay: eventTypes.canPlay,
topCanPlayThrough: eventTypes.canPlayThrough,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topDurationChange: eventTypes.durationChange,
topEmptied: eventTypes.emptied,
topEncrypted: eventTypes.encrypted,
topEnded: eventTypes.ended,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topInvalid: eventTypes.invalid,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topLoadedData: eventTypes.loadedData,
topLoadedMetadata: eventTypes.loadedMetadata,
topLoadStart: eventTypes.loadStart,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topPause: eventTypes.pause,
topPlay: eventTypes.play,
topPlaying: eventTypes.playing,
topProgress: eventTypes.progress,
topRateChange: eventTypes.rateChange,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSeeked: eventTypes.seeked,
topSeeking: eventTypes.seeking,
topStalled: eventTypes.stalled,
topSubmit: eventTypes.submit,
topSuspend: eventTypes.suspend,
topTimeUpdate: eventTypes.timeUpdate,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topTransitionEnd: eventTypes.transitionEnd,
topVolumeChange: eventTypes.volumeChange,
topWaiting: eventTypes.waiting,
topWheel: eventTypes.wheel
};
for (var type in topLevelEventsToDispatchConfig) topLevelEventsToDispatchConfig[type].dependencies = [ type ];
var ON_CLICK_KEY = keyOf({
onClick: null
}), onClickListeners = {}, SimpleEventPlugin = {
eventTypes: eventTypes,
extractEvents: function(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) return null;
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topAbort:
case topLevelTypes.topCanPlay:
case topLevelTypes.topCanPlayThrough:
case topLevelTypes.topDurationChange:
case topLevelTypes.topEmptied:
case topLevelTypes.topEncrypted:
case topLevelTypes.topEnded:
case topLevelTypes.topError:
case topLevelTypes.topInput:
case topLevelTypes.topInvalid:
case topLevelTypes.topLoad:
case topLevelTypes.topLoadedData:
case topLevelTypes.topLoadedMetadata:
case topLevelTypes.topLoadStart:
case topLevelTypes.topPause:
case topLevelTypes.topPlay:
case topLevelTypes.topPlaying:
case topLevelTypes.topProgress:
case topLevelTypes.topRateChange:
case topLevelTypes.topReset:
case topLevelTypes.topSeeked:
case topLevelTypes.topSeeking:
case topLevelTypes.topStalled:
case topLevelTypes.topSubmit:
case topLevelTypes.topSuspend:
case topLevelTypes.topTimeUpdate:
case topLevelTypes.topVolumeChange:
case topLevelTypes.topWaiting:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// Firefox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (0 === getEventCharCode(nativeEvent)) return null;
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (2 === nativeEvent.button) return null;
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topAnimationEnd:
case topLevelTypes.topAnimationIteration:
case topLevelTypes.topAnimationStart:
EventConstructor = SyntheticAnimationEvent;
break;
case topLevelTypes.topTransitionEnd:
EventConstructor = SyntheticTransitionEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
}
EventConstructor ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "SimpleEventPlugin: Unhandled event type, `%s`.", topLevelType) : invariant(!1);
var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
return EventPropagators.accumulateTwoPhaseDispatches(event), event;
},
didPutListener: function(inst, registrationName, listener) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
if (registrationName === ON_CLICK_KEY) {
var id = inst._rootNodeID, node = ReactDOMComponentTree.getNodeFromInstance(inst);
onClickListeners[id] || (onClickListeners[id] = EventListener.listen(node, "click", emptyFunction));
}
},
willDeleteListener: function(inst, registrationName) {
if (registrationName === ON_CLICK_KEY) {
var id = inst._rootNodeID;
onClickListeners[id].remove(), delete onClickListeners[id];
}
}
};
module.exports = SimpleEventPlugin;
}).call(exports, __webpack_require__(17));
}, /* 153 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticAnimationEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticEvent = __webpack_require__(34), AnimationEventInterface = {
animationName: null,
elapsedTime: null,
pseudoElement: null
};
SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface), module.exports = SyntheticAnimationEvent;
}, /* 154 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticClipboardEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticEvent = __webpack_require__(34), ClipboardEventInterface = {
clipboardData: function(event) {
return "clipboardData" in event ? event.clipboardData : window.clipboardData;
}
};
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface), module.exports = SyntheticClipboardEvent;
}, /* 155 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticFocusEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticUIEvent = __webpack_require__(61), FocusEventInterface = {
relatedTarget: null
};
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface), module.exports = SyntheticFocusEvent;
}, /* 156 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticKeyboardEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticUIEvent = __webpack_require__(61), getEventCharCode = __webpack_require__(157), getEventKey = __webpack_require__(158), getEventModifierState = __webpack_require__(63), KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function(event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
return "keypress" === event.type ? getEventCharCode(event) : 0;
},
keyCode: function(event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
return "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
},
which: function(event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
return "keypress" === event.type ? getEventCharCode(event) : "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
}
};
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface), module.exports = SyntheticKeyboardEvent;
}, /* 157 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventCharCode
*/
"use strict";
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode, keyCode = nativeEvent.keyCode;
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
return "charCode" in nativeEvent ? (charCode = nativeEvent.charCode, 0 === charCode && 13 === keyCode && (charCode = 13)) : charCode = keyCode,
charCode >= 32 || 13 === charCode ? charCode : 0;
}
module.exports = getEventCharCode;
}, /* 158 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventKey
*/
"use strict";
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if ("Unidentified" !== key) return key;
}
// Browser does not implement `key`, polyfill as much of it as we can.
if ("keypress" === nativeEvent.type) {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return 13 === charCode ? "Enter" : String.fromCharCode(charCode);
}
return "keydown" === nativeEvent.type || "keyup" === nativeEvent.type ? translateToKey[nativeEvent.keyCode] || "Unidentified" : "";
}
var getEventCharCode = __webpack_require__(157), normalizeKey = {
Esc: "Escape",
Spacebar: " ",
Left: "ArrowLeft",
Up: "ArrowUp",
Right: "ArrowRight",
Down: "ArrowDown",
Del: "Delete",
Win: "OS",
Menu: "ContextMenu",
Apps: "ContextMenu",
Scroll: "ScrollLock",
MozPrintableKey: "Unidentified"
}, translateToKey = {
8: "Backspace",
9: "Tab",
12: "Clear",
13: "Enter",
16: "Shift",
17: "Control",
18: "Alt",
19: "Pause",
20: "CapsLock",
27: "Escape",
32: " ",
33: "PageUp",
34: "PageDown",
35: "End",
36: "Home",
37: "ArrowLeft",
38: "ArrowUp",
39: "ArrowRight",
40: "ArrowDown",
45: "Insert",
46: "Delete",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12",
144: "NumLock",
145: "ScrollLock",
224: "Meta"
};
module.exports = getEventKey;
}, /* 159 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticDragEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticMouseEvent = __webpack_require__(60), DragEventInterface = {
dataTransfer: null
};
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface), module.exports = SyntheticDragEvent;
}, /* 160 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticTouchEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticUIEvent = __webpack_require__(61), getEventModifierState = __webpack_require__(63), TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface), module.exports = SyntheticTouchEvent;
}, /* 161 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticTransitionEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticEvent = __webpack_require__(34), TransitionEventInterface = {
propertyName: null,
elapsedTime: null,
pseudoElement: null
};
SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface),
module.exports = SyntheticTransitionEvent;
}, /* 162 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticWheelEvent
*/
"use strict";
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
var SyntheticMouseEvent = __webpack_require__(60), WheelEventInterface = {
deltaX: function(event) {
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0;
},
deltaY: function(event) {
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0;
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface), module.exports = SyntheticWheelEvent;
}, /* 163 */
/***/
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 ReactServerRendering
*/
"use strict";
/**
* @param {ReactElement} element
* @return {string} the HTML markup
*/
function renderToStringImpl(element, makeStaticMarkup) {
var transaction;
try {
return ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy),
transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup), transaction.perform(function() {
"production" !== process.env.NODE_ENV && ReactInstrumentation.debugTool.onBeginFlush();
var componentInstance = instantiateReactComponent(element), markup = ReactReconciler.mountComponent(componentInstance, transaction, null, ReactDOMContainerInfo(), emptyObject);
return "production" !== process.env.NODE_ENV && (ReactInstrumentation.debugTool.onUnmountComponent(componentInstance._debugID),
ReactInstrumentation.debugTool.onEndFlush()), makeStaticMarkup || (markup = ReactMarkupChecksum.addChecksumToMarkup(markup)),
markup;
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction), // Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
/**
* Render a ReactElement to its initial HTML. This should only be used on the
* server.
* See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring
*/
function renderToString(element) {
return ReactElement.isValidElement(element) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "renderToString(): You must pass a valid ReactElement.") : invariant(!1),
renderToStringImpl(element, !1);
}
/**
* Similar to renderToString, except this doesn't create extra DOM attributes
* such as data-react-id that React uses internally.
* See https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup
*/
function renderToStaticMarkup(element) {
return ReactElement.isValidElement(element) ? void 0 : "production" !== process.env.NODE_ENV ? invariant(!1, "renderToStaticMarkup(): You must pass a valid ReactElement.") : invariant(!1),
renderToStringImpl(element, !0);
}
var ReactDOMContainerInfo = __webpack_require__(164), ReactDefaultBatchingStrategy = __webpack_require__(134), ReactElement = __webpack_require__(103), ReactInstrumentation = __webpack_require__(44), ReactMarkupChecksum = __webpack_require__(165), ReactReconciler = __webpack_require__(51), ReactServerBatchingStrategy = __webpack_require__(167), ReactServerRenderingTransaction = __webpack_require__(128), ReactUpdates = __webpack_require__(41), emptyObject = __webpack_require__(123), instantiateReactComponent = __webpack_require__(118), invariant = __webpack_require__(18);
module.exports = {
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup
};
}).call(exports, __webpack_require__(17));
}, /* 164 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMContainerInfo
*/
"use strict";
function ReactDOMContainerInfo(topLevelWrapper, node) {
var info = {
_topLevelWrapper: topLevelWrapper,
_idCounter: 1,
_ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null,
_node: node,
_tag: node ? node.nodeName.toLowerCase() : null,
_namespaceURI: node ? node.namespaceURI : null
};
return "production" !== process.env.NODE_ENV && (info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null),
info;
}
var validateDOMNesting = __webpack_require__(130), DOC_NODE_TYPE = 9;
module.exports = ReactDOMContainerInfo;
}).call(exports, __webpack_require__(17));
}, /* 165 */
/***/
function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMarkupChecksum
*/
"use strict";
var adler32 = __webpack_require__(166), TAG_END = /\/?>/, COMMENT_START = /^<\!\-\-/, ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: "data-react-checksum",
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function(markup) {
var checksum = adler32(markup);
// Add checksum (handle both parent tags, comments and self-closing tags)
// Add checksum (handle both parent tags, comments and self-closing tags)
return COMMENT_START.test(markup) ? markup : markup.replace(TAG_END, " " + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function(markup, element) {
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
}, /* 166 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule adler32
*/
"use strict";
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
for (var a = 1, b = 0, i = 0, l = data.length, m = -4 & l; m > i; ) {
for (var n = Math.min(i + 4096, m); n > i; i += 4) b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
a %= MOD, b %= MOD;
}
for (;l > i; i++) b += a += data.charCodeAt(i);
return a %= MOD, b %= MOD, a | b << 16;
}
var MOD = 65521;
module.exports = adler32;
}, /* 167 */
/***/
function(module, exports) {
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerBatchingStrategy
*/
"use strict";
var ReactServerBatchingStrategy = {
isBatchingUpdates: !1,
batchedUpdates: function(callback) {}
};
module.exports = ReactServerBatchingStrategy;
}, /* 168 */
/***/
function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactVersion
*/
"use strict";
module.exports = "15.1.0";
}, /* 169 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.Collection = exports["default"] = void 0;
var _Collection2 = __webpack_require__(170), _Collection3 = _interopRequireDefault(_Collection2);
exports["default"] = _Collection3["default"], exports.Collection = _Collection3["default"];
}, /* 170 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]);
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
function defaultCellGroupRenderer(_ref4) {
var cellRenderer = _ref4.cellRenderer, cellSizeAndPositionGetter = _ref4.cellSizeAndPositionGetter, indices = _ref4.indices, isScrolling = _ref4.isScrolling;
return indices.map(function(index) {
var cellMetadata = cellSizeAndPositionGetter({
index: index
}), renderedCell = cellRenderer({
index: index,
isScrolling: isScrolling
});
return null == renderedCell || renderedCell === !1 ? null : _react2["default"].createElement("div", {
className: "Collection__cell",
key: index,
style: {
height: cellMetadata.height,
left: cellMetadata.x,
top: cellMetadata.y,
width: cellMetadata.width
}
}, renderedCell);
}).filter(function(renderedCell) {
return !!renderedCell;
});
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}, _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _CollectionView = __webpack_require__(171), _CollectionView2 = _interopRequireDefault(_CollectionView), _calculateSizeAndPositionData2 = __webpack_require__(178), _calculateSizeAndPositionData3 = _interopRequireDefault(_calculateSizeAndPositionData2), _getUpdatedOffsetForIndex = __webpack_require__(181), _getUpdatedOffsetForIndex2 = _interopRequireDefault(_getUpdatedOffsetForIndex), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), Collection = function(_Component) {
function Collection(props, context) {
_classCallCheck(this, Collection);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Collection).call(this, props, context));
return _this._cellMetadata = [], _this._lastRenderedCellIndices = [], _this;
}
return _inherits(Collection, _Component), _createClass(Collection, [ {
key: "recomputeCellSizesAndPositions",
value: function() {
this.refs.CollectionView.recomputeCellSizesAndPositions();
}
}, {
key: "render",
value: function() {
var props = _objectWithoutProperties(this.props, []);
return _react2["default"].createElement(_CollectionView2["default"], _extends({
cellLayoutManager: this,
ref: "CollectionView"
}, props));
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "calculateSizeAndPositionData",
value: function() {
var _props = this.props, cellCount = _props.cellCount, cellSizeAndPositionGetter = _props.cellSizeAndPositionGetter, sectionSize = _props.sectionSize, data = (0,
_calculateSizeAndPositionData3["default"])({
cellCount: cellCount,
cellSizeAndPositionGetter: cellSizeAndPositionGetter,
sectionSize: sectionSize
});
this._cellMetadata = data.cellMetadata, this._sectionManager = data.sectionManager,
this._height = data.height, this._width = data.width;
}
}, {
key: "getLastRenderedIndices",
value: function() {
return this._lastRenderedCellIndices;
}
}, {
key: "getScrollPositionForCell",
value: function(_ref) {
var align = _ref.align, cellIndex = _ref.cellIndex, height = _ref.height, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, width = _ref.width, cellCount = this.props.cellCount;
if (cellIndex >= 0 && cellCount > cellIndex) {
var cellMetadata = this._cellMetadata[cellIndex];
scrollLeft = (0, _getUpdatedOffsetForIndex2["default"])({
align: align,
cellOffset: cellMetadata.x,
cellSize: cellMetadata.width,
containerSize: width,
currentOffset: scrollLeft,
targetIndex: cellIndex
}), scrollTop = (0, _getUpdatedOffsetForIndex2["default"])({
align: align,
cellOffset: cellMetadata.y,
cellSize: cellMetadata.height,
containerSize: height,
currentOffset: scrollTop,
targetIndex: cellIndex
});
}
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
};
}
}, {
key: "getTotalSize",
value: function() {
return {
height: this._height,
width: this._width
};
}
}, {
key: "cellRenderers",
value: function(_ref2) {
var _this2 = this, height = _ref2.height, isScrolling = _ref2.isScrolling, width = _ref2.width, x = _ref2.x, y = _ref2.y, _props2 = this.props, cellGroupRenderer = _props2.cellGroupRenderer, cellRenderer = _props2.cellRenderer;
return this._lastRenderedCellIndices = this._sectionManager.getCellIndices({
height: height,
width: width,
x: x,
y: y
}), cellGroupRenderer({
cellRenderer: cellRenderer,
cellSizeAndPositionGetter: function(_ref3) {
var index = _ref3.index;
return _this2._sectionManager.getCellMetadata({
index: index
});
},
indices: this._lastRenderedCellIndices,
isScrolling: isScrolling
});
}
} ]), Collection;
}(_react.Component);
Collection.propTypes = {
"aria-label": _react.PropTypes.string,
cellCount: _react.PropTypes.number.isRequired,
cellGroupRenderer: _react.PropTypes.func.isRequired,
cellRenderer: _react.PropTypes.func.isRequired,
cellSizeAndPositionGetter: _react.PropTypes.func.isRequired,
sectionSize: _react.PropTypes.number
}, Collection.defaultProps = {
"aria-label": "grid",
cellGroupRenderer: defaultCellGroupRenderer
}, exports["default"] = Collection;
}, /* 171 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}, _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _createCallbackMemoizer = __webpack_require__(173), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _scrollbarSize = __webpack_require__(174), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _raf = __webpack_require__(176), _raf2 = _interopRequireDefault(_raf), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = {
OBSERVED: "observed",
REQUESTED: "requested"
}, CollectionView = function(_Component) {
function CollectionView(props, context) {
_classCallCheck(this, CollectionView);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CollectionView).call(this, props, context));
return _this.state = {
calculateSizeAndPositionDataOnNextUpdate: !1,
isScrolling: !1,
scrollLeft: 0,
scrollTop: 0
}, _this._onSectionRenderedMemoizer = (0, _createCallbackMemoizer2["default"])(),
_this._onScrollMemoizer = (0, _createCallbackMemoizer2["default"])(!1), _this._invokeOnSectionRenderedHelper = _this._invokeOnSectionRenderedHelper.bind(_this),
_this._onScroll = _this._onScroll.bind(_this), _this._updateScrollPositionForScrollToCell = _this._updateScrollPositionForScrollToCell.bind(_this),
_this;
}
return _inherits(CollectionView, _Component), _createClass(CollectionView, [ {
key: "recomputeCellSizesAndPositions",
value: function() {
this.setState({
calculateSizeAndPositionDataOnNextUpdate: !0
});
}
}, {
key: "componentDidMount",
value: function() {
var _props = this.props, cellLayoutManager = _props.cellLayoutManager, scrollLeft = _props.scrollLeft, scrollToCell = _props.scrollToCell, scrollTop = _props.scrollTop;
this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2["default"])(),
this._scrollbarSizeMeasured = !0, this.setState({})), scrollToCell >= 0 ? this._updateScrollPositionForScrollToCell() : (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({
scrollLeft: scrollLeft,
scrollTop: scrollTop
}), this._invokeOnSectionRenderedHelper();
var _cellLayoutManager$ge = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge.height, totalWidth = _cellLayoutManager$ge.width;
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft || 0,
scrollTop: scrollTop || 0,
totalHeight: totalHeight,
totalWidth: totalWidth
});
}
}, {
key: "componentDidUpdate",
value: function(prevProps, prevState) {
var _props2 = this.props, height = _props2.height, scrollToCell = _props2.scrollToCell, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollToAlignment = _state.scrollToAlignment, scrollTop = _state.scrollTop;
scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this.refs.scrollingContainer.scrollLeft && (this.refs.scrollingContainer.scrollLeft = scrollLeft),
scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this.refs.scrollingContainer.scrollTop && (this.refs.scrollingContainer.scrollTop = scrollTop)),
height === prevProps.height && scrollToAlignment === prevProps.scrollToAlignment && scrollToCell === prevProps.scrollToCell && width === prevProps.width || this._updateScrollPositionForScrollToCell(),
this._invokeOnSectionRenderedHelper();
}
}, {
key: "componentWillMount",
value: function() {
var cellLayoutManager = this.props.cellLayoutManager;
cellLayoutManager.calculateSizeAndPositionData(), this._scrollbarSize = (0, _scrollbarSize2["default"])(),
void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0;
}
}, {
key: "componentWillUnmount",
value: function() {
this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId),
this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId);
}
}, {
key: "componentWillUpdate",
value: function(nextProps, nextState) {
0 !== nextProps.cellCount || 0 === nextState.scrollLeft && 0 === nextState.scrollTop ? nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({
scrollLeft: nextProps.scrollLeft,
scrollTop: nextProps.scrollTop
}) : this._setScrollPosition({
scrollLeft: 0,
scrollTop: 0
}), (nextProps.cellCount !== this.props.cellCount || nextProps.cellLayoutManager !== this.props.cellLayoutManager || nextState.calculateSizeAndPositionDataOnNextUpdate) && nextProps.cellLayoutManager.calculateSizeAndPositionData(),
nextState.calculateSizeAndPositionDataOnNextUpdate && this.setState({
calculateSizeAndPositionDataOnNextUpdate: !1
});
}
}, {
key: "render",
value: function() {
var _props3 = this.props, cellLayoutManager = _props3.cellLayoutManager, className = _props3.className, height = _props3.height, noContentRenderer = _props3.noContentRenderer, style = _props3.style, width = _props3.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, childrenToDisplay = height > 0 && width > 0 ? cellLayoutManager.cellRenderers({
height: height,
isScrolling: isScrolling,
width: width,
x: scrollLeft,
y: scrollTop
}) : [], _cellLayoutManager$ge2 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge2.height, totalWidth = _cellLayoutManager$ge2.width, collectionStyle = _extends({}, style, {
height: height,
width: width
}), verticalScrollBarSize = totalHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalWidth > width ? this._scrollbarSize : 0;
return width >= totalWidth + verticalScrollBarSize && (collectionStyle.overflowX = "hidden"),
height >= totalHeight + horizontalScrollBarSize && (collectionStyle.overflowY = "hidden"),
_react2["default"].createElement("div", {
ref: "scrollingContainer",
"aria-label": this.props["aria-label"],
className: (0, _classnames2["default"])("Collection", className),
onScroll: this._onScroll,
role: "grid",
style: collectionStyle,
tabIndex: 0
}, childrenToDisplay.length > 0 && _react2["default"].createElement("div", {
className: "Collection__innerScrollContainer",
style: {
height: totalHeight,
maxHeight: totalHeight,
maxWidth: totalWidth,
pointerEvents: isScrolling ? "none" : "auto",
width: totalWidth
}
}, childrenToDisplay), 0 === childrenToDisplay.length && noContentRenderer());
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_enablePointerEventsAfterDelay",
value: function() {
var _this2 = this;
this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId),
this._disablePointerEventsTimeoutId = setTimeout(function() {
_this2._disablePointerEventsTimeoutId = null, _this2.setState({
isScrolling: !1
});
}, IS_SCROLLING_TIMEOUT);
}
}, {
key: "_invokeOnSectionRenderedHelper",
value: function() {
var _props4 = this.props, cellLayoutManager = _props4.cellLayoutManager, onSectionRendered = _props4.onSectionRendered;
this._onSectionRenderedMemoizer({
callback: onSectionRendered,
indices: {
indices: cellLayoutManager.getLastRenderedIndices()
}
});
}
}, {
key: "_invokeOnScrollMemoizer",
value: function(_ref) {
var _this3 = this, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, totalHeight = _ref.totalHeight, totalWidth = _ref.totalWidth;
this._onScrollMemoizer({
callback: function(_ref2) {
var scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, _props5 = _this3.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width;
onScroll({
clientHeight: height,
clientWidth: width,
scrollHeight: totalHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: totalWidth
});
},
indices: {
scrollLeft: scrollLeft,
scrollTop: scrollTop
}
});
}
}, {
key: "_setNextState",
value: function(state) {
var _this4 = this;
this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId),
this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() {
_this4._setNextStateAnimationFrameId = null, _this4.setState(state);
});
}
}, {
key: "_setScrollPosition",
value: function(_ref3) {
var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, newState = {
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED
};
scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop),
(scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState);
}
}, {
key: "_updateScrollPositionForScrollToCell",
value: function() {
var _props6 = this.props, cellLayoutManager = _props6.cellLayoutManager, height = _props6.height, scrollToAlignment = _props6.scrollToAlignment, scrollToCell = _props6.scrollToCell, width = _props6.width, _state3 = this.state, scrollLeft = _state3.scrollLeft, scrollTop = _state3.scrollTop;
if (scrollToCell >= 0) {
var scrollPosition = cellLayoutManager.getScrollPositionForCell({
align: scrollToAlignment,
cellIndex: scrollToCell,
height: height,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
width: width
});
scrollPosition.scrollLeft === scrollLeft && scrollPosition.scrollTop === scrollTop || this._setScrollPosition(scrollPosition);
}
}
}, {
key: "_onScroll",
value: function(event) {
if (event.target === this.refs.scrollingContainer) {
this._enablePointerEventsAfterDelay();
var _props7 = this.props, cellLayoutManager = _props7.cellLayoutManager, height = _props7.height, width = _props7.width, scrollbarSize = this._scrollbarSize, _cellLayoutManager$ge3 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge3.height, totalWidth = _cellLayoutManager$ge3.width, scrollLeft = Math.max(0, Math.min(totalWidth - width + scrollbarSize, event.target.scrollLeft)), scrollTop = Math.max(0, Math.min(totalHeight - height + scrollbarSize, event.target.scrollTop));
if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) {
var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED;
this.state.isScrolling || this.setState({
isScrolling: !0
}), this._setNextState({
isScrolling: !0,
scrollLeft: scrollLeft,
scrollPositionChangeReason: scrollPositionChangeReason,
scrollTop: scrollTop
});
}
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft,
scrollTop: scrollTop,
totalWidth: totalWidth,
totalHeight: totalHeight
});
}
}
} ]), CollectionView;
}(_react.Component);
CollectionView.propTypes = {
"aria-label": _react.PropTypes.string,
cellCount: _react.PropTypes.number.isRequired,
cellLayoutManager: _react.PropTypes.object.isRequired,
className: _react.PropTypes.string,
height: _react.PropTypes.number.isRequired,
noContentRenderer: _react.PropTypes.func.isRequired,
onScroll: _react.PropTypes.func.isRequired,
onSectionRendered: _react.PropTypes.func.isRequired,
scrollLeft: _react.PropTypes.number,
scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired,
scrollToCell: _react.PropTypes.number,
scrollTop: _react.PropTypes.number,
style: _react.PropTypes.object,
width: _react.PropTypes.number.isRequired
}, CollectionView.defaultProps = {
"aria-label": "grid",
noContentRenderer: function() {
return null;
},
onScroll: function() {
return null;
},
onSectionRendered: function() {
return null;
},
scrollToAlignment: "auto",
style: {}
}, exports["default"] = CollectionView;
}, /* 172 */
/***/
function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
!function() {
"use strict";
function classNames() {
for (var classes = [], i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
var argType = typeof arg;
if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key);
}
}
return classes.join(" ");
}
var hasOwn = {}.hasOwnProperty;
"undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [],
__WEBPACK_AMD_DEFINE_RESULT__ = function() {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), !(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)));
}();
}, /* 173 */
/***/
function(module, exports) {
"use strict";
function createCallbackMemoizer() {
var requireAllKeys = arguments.length <= 0 || void 0 === arguments[0] ? !0 : arguments[0], cachedIndices = {};
return function(_ref) {
var callback = _ref.callback, indices = _ref.indices, keys = Object.keys(indices), allInitialized = !requireAllKeys || keys.every(function(key) {
var value = indices[key];
return Array.isArray(value) ? value.length > 0 : value >= 0;
}), indexChanged = keys.length !== Object.keys(cachedIndices).length || keys.some(function(key) {
var cachedValue = cachedIndices[key], value = indices[key];
return Array.isArray(value) ? cachedValue.join(",") !== value.join(",") : cachedValue !== value;
});
cachedIndices = indices, allInitialized && indexChanged && callback(indices);
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = createCallbackMemoizer;
}, /* 174 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
var size, canUseDOM = __webpack_require__(175);
module.exports = function(recalc) {
if ((!size || recalc) && 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;
};
}, /* 175 */
/***/
function(module, exports) {
"use strict";
module.exports = !("undefined" == typeof window || !window.document || !window.document.createElement);
}, /* 176 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(global) {
for (var now = __webpack_require__(177), root = "undefined" == typeof window ? global : window, vendors = [ "moz", "webkit" ], suffix = "AnimationFrame", raf = root["request" + suffix], caf = root["cancel" + suffix] || root["cancelRequest" + suffix], i = 0; !raf && i < vendors.length; i++) raf = root[vendors[i] + "Request" + suffix],
caf = root[vendors[i] + "Cancel" + suffix] || root[vendors[i] + "CancelRequest" + suffix];
// Some versions of FF have rAF but not cAF
if (!raf || !caf) {
var last = 0, id = 0, queue = [], frameDuration = 1e3 / 60;
raf = function(callback) {
if (0 === queue.length) {
var _now = now(), next = Math.max(0, frameDuration - (_now - last));
last = next + _now, setTimeout(function() {
var cp = queue.slice(0);
// Clear queue here to prevent
// callbacks from appending listeners
// to the current frame's queue
queue.length = 0;
for (var i = 0; i < cp.length; i++) if (!cp[i].cancelled) try {
cp[i].callback(last);
} catch (e) {
setTimeout(function() {
throw e;
}, 0);
}
}, Math.round(next));
}
return queue.push({
handle: ++id,
callback: callback,
cancelled: !1
}), id;
}, caf = function(handle) {
for (var i = 0; i < queue.length; i++) queue[i].handle === handle && (queue[i].cancelled = !0);
};
}
module.exports = function(fn) {
// Wrap in a new function to prevent
// `cancel` potentially being assigned
// to the native rAF function
return raf.call(root, fn);
}, module.exports.cancel = function() {
caf.apply(root, arguments);
}, module.exports.polyfill = function() {
root.requestAnimationFrame = raf, root.cancelAnimationFrame = caf;
};
}).call(exports, function() {
return this;
}());
}, /* 177 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
// Generated by CoffeeScript 1.7.1
(function() {
var getNanoSeconds, hrtime, loadTime;
"undefined" != typeof performance && null !== performance && performance.now ? module.exports = function() {
return performance.now();
} : "undefined" != typeof process && null !== process && process.hrtime ? (module.exports = function() {
return (getNanoSeconds() - loadTime) / 1e6;
}, hrtime = process.hrtime, getNanoSeconds = function() {
var hr;
return hr = hrtime(), 1e9 * hr[0] + hr[1];
}, loadTime = getNanoSeconds()) : Date.now ? (module.exports = function() {
return Date.now() - loadTime;
}, loadTime = Date.now()) : (module.exports = function() {
return new Date().getTime() - loadTime;
}, loadTime = new Date().getTime());
}).call(this);
}).call(exports, __webpack_require__(17));
}, /* 178 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function calculateSizeAndPositionData(_ref) {
for (var cellCount = _ref.cellCount, cellSizeAndPositionGetter = _ref.cellSizeAndPositionGetter, sectionSize = _ref.sectionSize, cellMetadata = [], sectionManager = new _SectionManager2["default"](sectionSize), height = 0, width = 0, index = 0; cellCount > index; index++) {
var cellMetadatum = cellSizeAndPositionGetter({
index: index
});
if (null == cellMetadatum.height || isNaN(cellMetadatum.height) || null == cellMetadatum.width || isNaN(cellMetadatum.width) || null == cellMetadatum.x || isNaN(cellMetadatum.x) || null == cellMetadatum.y || isNaN(cellMetadatum.y)) throw Error("Invalid metadata returned for cell " + index + ":\n x:" + cellMetadatum.x + ", y:" + cellMetadatum.y + ", width:" + cellMetadatum.width + ", height:" + cellMetadatum.height);
height = Math.max(height, cellMetadatum.y + cellMetadatum.height), width = Math.max(width, cellMetadatum.x + cellMetadatum.width),
cellMetadata[index] = cellMetadatum, sectionManager.registerCell({
cellMetadatum: cellMetadatum,
index: index
});
}
return {
cellMetadata: cellMetadata,
height: height,
sectionManager: sectionManager,
width: width
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = calculateSizeAndPositionData;
var _SectionManager = __webpack_require__(179), _SectionManager2 = _interopRequireDefault(_SectionManager);
}, /* 179 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _Section = __webpack_require__(180), _Section2 = _interopRequireDefault(_Section), SECTION_SIZE = 100, SectionManager = function() {
function SectionManager() {
var sectionSize = arguments.length <= 0 || void 0 === arguments[0] ? SECTION_SIZE : arguments[0];
_classCallCheck(this, SectionManager), this._sectionSize = sectionSize, this._cellMetadata = [],
this._sections = {};
}
return _createClass(SectionManager, [ {
key: "getCellIndices",
value: function(_ref) {
var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y, indices = {};
return this.getSections({
height: height,
width: width,
x: x,
y: y
}).forEach(function(section) {
return section.getCellIndices().forEach(function(index) {
indices[index] = index;
});
}), Object.keys(indices).map(function(index) {
return indices[index];
});
}
}, {
key: "getCellMetadata",
value: function(_ref2) {
var index = _ref2.index;
return this._cellMetadata[index];
}
}, {
key: "getSections",
value: function(_ref3) {
for (var height = _ref3.height, width = _ref3.width, x = _ref3.x, y = _ref3.y, sectionXStart = Math.floor(x / this._sectionSize), sectionXStop = Math.floor((x + width - 1) / this._sectionSize), sectionYStart = Math.floor(y / this._sectionSize), sectionYStop = Math.floor((y + height - 1) / this._sectionSize), sections = [], sectionX = sectionXStart; sectionXStop >= sectionX; sectionX++) for (var sectionY = sectionYStart; sectionYStop >= sectionY; sectionY++) {
var key = sectionX + "." + sectionY;
this._sections[key] || (this._sections[key] = new _Section2["default"]({
height: this._sectionSize,
width: this._sectionSize,
x: sectionX * this._sectionSize,
y: sectionY * this._sectionSize
})), sections.push(this._sections[key]);
}
return sections;
}
}, {
key: "getTotalSectionCount",
value: function() {
return Object.keys(this._sections).length;
}
}, {
key: "toString",
value: function() {
var _this = this;
return Object.keys(this._sections).map(function(index) {
return _this._sections[index].toString();
});
}
}, {
key: "registerCell",
value: function(_ref4) {
var cellMetadatum = _ref4.cellMetadatum, index = _ref4.index;
this._cellMetadata[index] = cellMetadatum, this.getSections(cellMetadatum).forEach(function(section) {
return section.addCellIndex({
index: index
});
});
}
} ]), SectionManager;
}();
exports["default"] = SectionManager;
}, /* 180 */
/***/
function(module, exports) {
"use strict";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), Section = function() {
function Section(_ref) {
var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y;
_classCallCheck(this, Section), this.height = height, this.width = width, this.x = x,
this.y = y, this._indexMap = {}, this._indices = [];
}
return _createClass(Section, [ {
key: "addCellIndex",
value: function(_ref2) {
var index = _ref2.index;
this._indexMap[index] || (this._indexMap[index] = !0, this._indices.push(index));
}
}, {
key: "getCellIndices",
value: function() {
return this._indices;
}
}, {
key: "toString",
value: function() {
return this.x + "," + this.y + " " + this.width + "x" + this.height;
}
} ]), Section;
}();
exports["default"] = Section;
}, /* 181 */
/***/
function(module, exports) {
"use strict";
function getUpdatedOffsetForIndex(_ref) {
var _ref$align = _ref.align, align = void 0 === _ref$align ? "auto" : _ref$align, cellOffset = _ref.cellOffset, cellSize = _ref.cellSize, containerSize = _ref.containerSize, currentOffset = _ref.currentOffset, maxOffset = cellOffset, minOffset = maxOffset - containerSize + cellSize;
switch (align) {
case "start":
return maxOffset;
case "end":
return minOffset;
case "center":
return maxOffset - (containerSize + cellSize) / 2;
default:
return Math.max(minOffset, Math.min(maxOffset, currentOffset));
}
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = getUpdatedOffsetForIndex;
}, /* 182 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.ColumnSizer = exports["default"] = void 0;
var _ColumnSizer2 = __webpack_require__(183), _ColumnSizer3 = _interopRequireDefault(_ColumnSizer2);
exports["default"] = _ColumnSizer3["default"], exports.ColumnSizer = _ColumnSizer3["default"];
}, /* 183 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(184), _Grid2 = _interopRequireDefault(_Grid), ColumnSizer = function(_Component) {
function ColumnSizer(props, context) {
_classCallCheck(this, ColumnSizer);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ColumnSizer).call(this, props, context));
return _this._registerChild = _this._registerChild.bind(_this), _this;
}
return _inherits(ColumnSizer, _Component), _createClass(ColumnSizer, [ {
key: "componentDidUpdate",
value: function(prevProps, prevState) {
var _props = this.props, columnMaxWidth = _props.columnMaxWidth, columnMinWidth = _props.columnMinWidth, columnCount = _props.columnCount, width = _props.width;
columnMaxWidth === prevProps.columnMaxWidth && columnMinWidth === prevProps.columnMinWidth && columnCount === prevProps.columnCount && width === prevProps.width || this._registeredChild && this._registeredChild.recomputeGridSize();
}
}, {
key: "render",
value: function() {
var _props2 = this.props, children = _props2.children, columnMaxWidth = _props2.columnMaxWidth, columnMinWidth = _props2.columnMinWidth, columnCount = _props2.columnCount, width = _props2.width, safeColumnMinWidth = columnMinWidth || 1, safeColumnMaxWidth = columnMaxWidth ? Math.min(columnMaxWidth, width) : width, columnWidth = width / columnCount;
columnWidth = Math.max(safeColumnMinWidth, columnWidth), columnWidth = Math.min(safeColumnMaxWidth, columnWidth),
columnWidth = Math.floor(columnWidth);
var adjustedWidth = Math.min(width, columnWidth * columnCount);
return children({
adjustedWidth: adjustedWidth,
getColumnWidth: function() {
return columnWidth;
},
registerChild: this._registerChild
});
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_registerChild",
value: function(child) {
if (null !== child && !(child instanceof _Grid2["default"])) throw Error("Unexpected child type registered; only Grid children are supported.");
this._registeredChild = child, this._registeredChild && this._registeredChild.recomputeGridSize();
}
} ]), ColumnSizer;
}(_react.Component);
ColumnSizer.propTypes = {
children: _react.PropTypes.func.isRequired,
columnMaxWidth: _react.PropTypes.number,
columnMinWidth: _react.PropTypes.number,
columnCount: _react.PropTypes.number.isRequired,
width: _react.PropTypes.number.isRequired
}, exports["default"] = ColumnSizer;
}, /* 184 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.defaultCellRangeRenderer = exports.Grid = exports["default"] = void 0;
var _Grid2 = __webpack_require__(185), _Grid3 = _interopRequireDefault(_Grid2), _defaultCellRangeRenderer2 = __webpack_require__(191), _defaultCellRangeRenderer3 = _interopRequireDefault(_defaultCellRangeRenderer2);
exports["default"] = _Grid3["default"], exports.Grid = _Grid3["default"], exports.defaultCellRangeRenderer = _defaultCellRangeRenderer3["default"];
}, /* 185 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}, _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _calculateSizeAndPositionDataAndUpdateScrollOffset = __webpack_require__(186), _calculateSizeAndPositionDataAndUpdateScrollOffset2 = _interopRequireDefault(_calculateSizeAndPositionDataAndUpdateScrollOffset), _ScalingCellSizeAndPositionManager = __webpack_require__(187), _ScalingCellSizeAndPositionManager2 = _interopRequireDefault(_ScalingCellSizeAndPositionManager), _createCallbackMemoizer = __webpack_require__(173), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _getOverscanIndices = __webpack_require__(189), _getOverscanIndices2 = _interopRequireDefault(_getOverscanIndices), _scrollbarSize = __webpack_require__(174), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _raf = __webpack_require__(176), _raf2 = _interopRequireDefault(_raf), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _updateScrollIndexHelper = __webpack_require__(190), _updateScrollIndexHelper2 = _interopRequireDefault(_updateScrollIndexHelper), _defaultCellRangeRenderer = __webpack_require__(191), _defaultCellRangeRenderer2 = _interopRequireDefault(_defaultCellRangeRenderer), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = {
OBSERVED: "observed",
REQUESTED: "requested"
}, Grid = function(_Component) {
function Grid(props, context) {
_classCallCheck(this, Grid);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Grid).call(this, props, context));
return _this.state = {
isScrolling: !1,
scrollLeft: 0,
scrollTop: 0
}, _this._onGridRenderedMemoizer = (0, _createCallbackMemoizer2["default"])(), _this._onScrollMemoizer = (0,
_createCallbackMemoizer2["default"])(!1), _this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this),
_this._invokeOnGridRenderedHelper = _this._invokeOnGridRenderedHelper.bind(_this),
_this._onScroll = _this._onScroll.bind(_this), _this._setNextStateCallback = _this._setNextStateCallback.bind(_this),
_this._updateScrollLeftForScrollToColumn = _this._updateScrollLeftForScrollToColumn.bind(_this),
_this._updateScrollTopForScrollToRow = _this._updateScrollTopForScrollToRow.bind(_this),
_this._columnWidthGetter = _this._wrapSizeGetter(props.columnWidth), _this._rowHeightGetter = _this._wrapSizeGetter(props.rowHeight),
_this._columnSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2["default"]({
cellCount: props.columnCount,
cellSizeGetter: function(index) {
return _this._columnWidthGetter(index);
},
estimatedCellSize: _this._getEstimatedColumnSize(props)
}), _this._rowSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2["default"]({
cellCount: props.rowCount,
cellSizeGetter: function(index) {
return _this._rowHeightGetter(index);
},
estimatedCellSize: _this._getEstimatedRowSize(props)
}), _this._cellCache = {}, _this;
}
return _inherits(Grid, _Component), _createClass(Grid, [ {
key: "measureAllCells",
value: function() {
var _props = this.props, columnCount = _props.columnCount, rowCount = _props.rowCount;
this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnCount - 1), this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1);
}
}, {
key: "recomputeGridSize",
value: function() {
var _ref = arguments.length <= 0 || void 0 === arguments[0] ? {} : arguments[0], _ref$columnIndex = _ref.columnIndex, columnIndex = void 0 === _ref$columnIndex ? 0 : _ref$columnIndex, _ref$rowIndex = _ref.rowIndex, rowIndex = void 0 === _ref$rowIndex ? 0 : _ref$rowIndex;
this._columnSizeAndPositionManager.resetCell(columnIndex), this._rowSizeAndPositionManager.resetCell(rowIndex),
this.forceUpdate();
}
}, {
key: "componentDidMount",
value: function() {
var _props2 = this.props, scrollLeft = _props2.scrollLeft, scrollToColumn = _props2.scrollToColumn, scrollTop = _props2.scrollTop, scrollToRow = _props2.scrollToRow;
this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2["default"])(),
this._scrollbarSizeMeasured = !0, this.setState({})), (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({
scrollLeft: scrollLeft,
scrollTop: scrollTop
}), (scrollToColumn >= 0 || scrollToRow >= 0) && (this._updateScrollLeftForScrollToColumn(),
this._updateScrollTopForScrollToRow()), this._invokeOnGridRenderedHelper(), this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft || 0,
scrollTop: scrollTop || 0,
totalColumnsWidth: this._columnSizeAndPositionManager.getTotalSize(),
totalRowsHeight: this._rowSizeAndPositionManager.getTotalSize()
});
}
}, {
key: "componentDidUpdate",
value: function(prevProps, prevState) {
var _this2 = this, _props3 = this.props, autoHeight = _props3.autoHeight, height = _props3.height, scrollToAlignment = _props3.scrollToAlignment, scrollToColumn = _props3.scrollToColumn, scrollToRow = _props3.scrollToRow, width = _props3.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop;
scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this.refs.scrollingContainer.scrollLeft && (this.refs.scrollingContainer.scrollLeft = scrollLeft),
!autoHeight && scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this.refs.scrollingContainer.scrollTop && (this.refs.scrollingContainer.scrollTop = scrollTop)),
(0, _updateScrollIndexHelper2["default"])({
cellSizeAndPositionManager: this._columnSizeAndPositionManager,
previousCellsCount: prevProps.columnCount,
previousCellSize: prevProps.columnWidth,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToColumn,
previousSize: prevProps.width,
scrollOffset: scrollLeft,
scrollToAlignment: scrollToAlignment,
scrollToIndex: scrollToColumn,
size: width,
updateScrollIndexCallback: function(scrollToColumn) {
return _this2._updateScrollLeftForScrollToColumn(_extends({}, _this2.props, {
scrollToColumn: scrollToColumn
}));
}
}), (0, _updateScrollIndexHelper2["default"])({
cellSizeAndPositionManager: this._rowSizeAndPositionManager,
previousCellsCount: prevProps.rowCount,
previousCellSize: prevProps.rowHeight,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToRow,
previousSize: prevProps.height,
scrollOffset: scrollTop,
scrollToAlignment: scrollToAlignment,
scrollToIndex: scrollToRow,
size: height,
updateScrollIndexCallback: function(scrollToRow) {
return _this2._updateScrollTopForScrollToRow(_extends({}, _this2.props, {
scrollToRow: scrollToRow
}));
}
}), this._invokeOnGridRenderedHelper();
}
}, {
key: "componentWillMount",
value: function() {
this._scrollbarSize = (0, _scrollbarSize2["default"])(), void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1,
this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0;
}
}, {
key: "componentWillUnmount",
value: function() {
this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId),
this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId);
}
}, {
key: "componentWillUpdate",
value: function(nextProps, nextState) {
var _this3 = this;
0 === nextProps.columnCount && 0 !== nextState.scrollLeft || 0 === nextProps.rowCount && 0 !== nextState.scrollTop ? this._setScrollPosition({
scrollLeft: 0,
scrollTop: 0
}) : nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({
scrollLeft: nextProps.scrollLeft,
scrollTop: nextProps.scrollTop
}), this._columnWidthGetter = this._wrapSizeGetter(nextProps.columnWidth), this._rowHeightGetter = this._wrapSizeGetter(nextProps.rowHeight),
this._columnSizeAndPositionManager.configure({
cellCount: nextProps.columnCount,
estimatedCellSize: this._getEstimatedColumnSize(nextProps)
}), this._rowSizeAndPositionManager.configure({
cellCount: nextProps.rowCount,
estimatedCellSize: this._getEstimatedRowSize(nextProps)
}), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2["default"])({
cellCount: this.props.columnCount,
cellSize: this.props.columnWidth,
computeMetadataCallback: function() {
return _this3._columnSizeAndPositionManager.resetCell(0);
},
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.columnCount,
nextCellSize: nextProps.columnWidth,
nextScrollToIndex: nextProps.scrollToColumn,
scrollToIndex: this.props.scrollToColumn,
updateScrollOffsetForScrollToIndex: function() {
return _this3._updateScrollLeftForScrollToColumn(nextProps, nextState);
}
}), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2["default"])({
cellCount: this.props.rowCount,
cellSize: this.props.rowHeight,
computeMetadataCallback: function() {
return _this3._rowSizeAndPositionManager.resetCell(0);
},
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.rowCount,
nextCellSize: nextProps.rowHeight,
nextScrollToIndex: nextProps.scrollToRow,
scrollToIndex: this.props.scrollToRow,
updateScrollOffsetForScrollToIndex: function() {
return _this3._updateScrollTopForScrollToRow(nextProps, nextState);
}
});
}
}, {
key: "render",
value: function() {
var _props4 = this.props, autoHeight = _props4.autoHeight, cellClassName = _props4.cellClassName, cellRenderer = _props4.cellRenderer, cellRangeRenderer = _props4.cellRangeRenderer, cellStyle = _props4.cellStyle, className = _props4.className, columnCount = _props4.columnCount, height = _props4.height, noContentRenderer = _props4.noContentRenderer, overscanColumnCount = _props4.overscanColumnCount, overscanRowCount = _props4.overscanRowCount, rowCount = _props4.rowCount, style = _props4.style, tabIndex = _props4.tabIndex, width = _props4.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, childrenToDisplay = [];
if (height > 0 && width > 0) {
var visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange({
containerSize: width,
offset: scrollLeft
}), visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange({
containerSize: height,
offset: scrollTop
}), horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment({
containerSize: width,
offset: scrollLeft
}), verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment({
containerSize: height,
offset: scrollTop
});
this._renderedColumnStartIndex = visibleColumnIndices.start, this._renderedColumnStopIndex = visibleColumnIndices.stop,
this._renderedRowStartIndex = visibleRowIndices.start, this._renderedRowStopIndex = visibleRowIndices.stop;
var overscanColumnIndices = (0, _getOverscanIndices2["default"])({
cellCount: columnCount,
overscanCellsCount: overscanColumnCount,
startIndex: this._renderedColumnStartIndex,
stopIndex: this._renderedColumnStopIndex
}), overscanRowIndices = (0, _getOverscanIndices2["default"])({
cellCount: rowCount,
overscanCellsCount: overscanRowCount,
startIndex: this._renderedRowStartIndex,
stopIndex: this._renderedRowStopIndex
});
this._columnStartIndex = overscanColumnIndices.overscanStartIndex, this._columnStopIndex = overscanColumnIndices.overscanStopIndex,
this._rowStartIndex = overscanRowIndices.overscanStartIndex, this._rowStopIndex = overscanRowIndices.overscanStopIndex,
childrenToDisplay = cellRangeRenderer({
cellCache: this._cellCache,
cellClassName: this._wrapCellClassNameGetter(cellClassName),
cellRenderer: cellRenderer,
cellStyle: this._wrapCellStyleGetter(cellStyle),
columnSizeAndPositionManager: this._columnSizeAndPositionManager,
columnStartIndex: this._columnStartIndex,
columnStopIndex: this._columnStopIndex,
horizontalOffsetAdjustment: horizontalOffsetAdjustment,
isScrolling: isScrolling,
rowSizeAndPositionManager: this._rowSizeAndPositionManager,
rowStartIndex: this._rowStartIndex,
rowStopIndex: this._rowStopIndex,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
verticalOffsetAdjustment: verticalOffsetAdjustment
});
}
var gridStyle = _extends({}, style, {
height: autoHeight ? "auto" : height,
width: width
}), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), verticalScrollBarSize = totalRowsHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalColumnsWidth > width ? this._scrollbarSize : 0;
width >= totalColumnsWidth + verticalScrollBarSize && (gridStyle.overflowX = "hidden"),
height >= totalRowsHeight + horizontalScrollBarSize && (gridStyle.overflowY = "hidden");
var showNoContentRenderer = 0 === childrenToDisplay.length && height > 0 && width > 0;
return _react2["default"].createElement("div", {
ref: "scrollingContainer",
"aria-label": this.props["aria-label"],
className: (0, _classnames2["default"])("Grid", className),
onScroll: this._onScroll,
role: "grid",
style: gridStyle,
tabIndex: tabIndex
}, childrenToDisplay.length > 0 && _react2["default"].createElement("div", {
className: "Grid__innerScrollContainer",
style: {
width: 1 === columnCount ? "auto" : totalColumnsWidth,
height: totalRowsHeight,
maxWidth: totalColumnsWidth,
maxHeight: totalRowsHeight,
pointerEvents: isScrolling ? "none" : "auto"
}
}, childrenToDisplay), showNoContentRenderer && noContentRenderer());
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_enablePointerEventsAfterDelay",
value: function() {
this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId),
this._disablePointerEventsTimeoutId = setTimeout(this._enablePointerEventsAfterDelayCallback, IS_SCROLLING_TIMEOUT);
}
}, {
key: "_enablePointerEventsAfterDelayCallback",
value: function() {
this._disablePointerEventsTimeoutId = null, this._cellCache = {}, this.setState({
isScrolling: !1
});
}
}, {
key: "_getEstimatedColumnSize",
value: function(props) {
return "number" == typeof props.columnWidth ? props.columnWidth : props.estimatedColumnSize;
}
}, {
key: "_getEstimatedRowSize",
value: function(props) {
return "number" == typeof props.rowHeight ? props.rowHeight : props.estimatedRowSize;
}
}, {
key: "_invokeOnGridRenderedHelper",
value: function() {
var onSectionRendered = this.props.onSectionRendered;
this._onGridRenderedMemoizer({
callback: onSectionRendered,
indices: {
columnOverscanStartIndex: this._columnStartIndex,
columnOverscanStopIndex: this._columnStopIndex,
columnStartIndex: this._renderedColumnStartIndex,
columnStopIndex: this._renderedColumnStopIndex,
rowOverscanStartIndex: this._rowStartIndex,
rowOverscanStopIndex: this._rowStopIndex,
rowStartIndex: this._renderedRowStartIndex,
rowStopIndex: this._renderedRowStopIndex
}
});
}
}, {
key: "_invokeOnScrollMemoizer",
value: function(_ref2) {
var _this4 = this, scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, totalColumnsWidth = _ref2.totalColumnsWidth, totalRowsHeight = _ref2.totalRowsHeight;
this._onScrollMemoizer({
callback: function(_ref3) {
var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, _props5 = _this4.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width;
onScroll({
clientHeight: height,
clientWidth: width,
scrollHeight: totalRowsHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: totalColumnsWidth
});
},
indices: {
scrollLeft: scrollLeft,
scrollTop: scrollTop
}
});
}
}, {
key: "_setNextState",
value: function(state) {
this._nextState = state, this._setNextStateAnimationFrameId || (this._setNextStateAnimationFrameId = (0,
_raf2["default"])(this._setNextStateCallback));
}
}, {
key: "_setNextStateCallback",
value: function() {
var state = this._nextState;
this._setNextStateAnimationFrameId = null, this._nextState = null, this.setState(state);
}
}, {
key: "_setScrollPosition",
value: function(_ref4) {
var scrollLeft = _ref4.scrollLeft, scrollTop = _ref4.scrollTop, newState = {
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED
};
scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop),
(scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState);
}
}, {
key: "_wrapCellClassNameGetter",
value: function(className) {
return this._wrapPropertyGetter(className);
}
}, {
key: "_wrapCellStyleGetter",
value: function(style) {
return this._wrapPropertyGetter(style);
}
}, {
key: "_wrapPropertyGetter",
value: function(value) {
return value instanceof Function ? value : function() {
return value;
};
}
}, {
key: "_wrapSizeGetter",
value: function(size) {
return this._wrapPropertyGetter(size);
}
}, {
key: "_updateScrollLeftForScrollToColumn",
value: function() {
var props = arguments.length <= 0 || void 0 === arguments[0] ? this.props : arguments[0], state = arguments.length <= 1 || void 0 === arguments[1] ? this.state : arguments[1], columnCount = props.columnCount, scrollToAlignment = props.scrollToAlignment, scrollToColumn = props.scrollToColumn, width = props.width, scrollLeft = state.scrollLeft;
if (scrollToColumn >= 0 && columnCount > 0) {
var targetIndex = Math.max(0, Math.min(columnCount - 1, scrollToColumn)), calculatedScrollLeft = this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({
align: scrollToAlignment,
containerSize: width,
currentOffset: scrollLeft,
targetIndex: targetIndex
});
scrollLeft !== calculatedScrollLeft && this._setScrollPosition({
scrollLeft: calculatedScrollLeft
});
}
}
}, {
key: "_updateScrollTopForScrollToRow",
value: function() {
var props = arguments.length <= 0 || void 0 === arguments[0] ? this.props : arguments[0], state = arguments.length <= 1 || void 0 === arguments[1] ? this.state : arguments[1], height = props.height, rowCount = props.rowCount, scrollToAlignment = props.scrollToAlignment, scrollToRow = props.scrollToRow, scrollTop = state.scrollTop;
if (scrollToRow >= 0 && rowCount > 0) {
var targetIndex = Math.max(0, Math.min(rowCount - 1, scrollToRow)), calculatedScrollTop = this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({
align: scrollToAlignment,
containerSize: height,
currentOffset: scrollTop,
targetIndex: targetIndex
});
scrollTop !== calculatedScrollTop && this._setScrollPosition({
scrollTop: calculatedScrollTop
});
}
}
}, {
key: "_onScroll",
value: function(event) {
if (event.target === this.refs.scrollingContainer) {
this._enablePointerEventsAfterDelay();
var _props6 = this.props, height = _props6.height, width = _props6.width, scrollbarSize = this._scrollbarSize, totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), scrollLeft = Math.min(Math.max(0, totalColumnsWidth - width + scrollbarSize), event.target.scrollLeft), scrollTop = Math.min(Math.max(0, totalRowsHeight - height + scrollbarSize), event.target.scrollTop);
if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) {
var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED;
this.state.isScrolling || this.setState({
isScrolling: !0
}), this._setNextState({
isScrolling: !0,
scrollLeft: scrollLeft,
scrollPositionChangeReason: scrollPositionChangeReason,
scrollTop: scrollTop
});
}
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft,
scrollTop: scrollTop,
totalColumnsWidth: totalColumnsWidth,
totalRowsHeight: totalRowsHeight
});
}
}
} ]), Grid;
}(_react.Component);
Grid.propTypes = {
"aria-label": _react.PropTypes.string,
autoHeight: _react.PropTypes.bool,
cellClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]),
cellStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]),
cellRenderer: _react.PropTypes.func.isRequired,
cellRangeRenderer: _react.PropTypes.func.isRequired,
className: _react.PropTypes.string,
columnCount: _react.PropTypes.number.isRequired,
columnWidth: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired,
estimatedColumnSize: _react.PropTypes.number.isRequired,
estimatedRowSize: _react.PropTypes.number.isRequired,
height: _react.PropTypes.number.isRequired,
noContentRenderer: _react.PropTypes.func.isRequired,
onScroll: _react.PropTypes.func.isRequired,
onSectionRendered: _react.PropTypes.func.isRequired,
overscanColumnCount: _react.PropTypes.number.isRequired,
overscanRowCount: _react.PropTypes.number.isRequired,
rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired,
rowCount: _react.PropTypes.number.isRequired,
scrollLeft: _react.PropTypes.number,
scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired,
scrollToColumn: _react.PropTypes.number,
scrollTop: _react.PropTypes.number,
scrollToRow: _react.PropTypes.number,
style: _react.PropTypes.object,
tabIndex: _react.PropTypes.number,
width: _react.PropTypes.number.isRequired
}, Grid.defaultProps = {
"aria-label": "grid",
cellStyle: {},
cellRangeRenderer: _defaultCellRangeRenderer2["default"],
estimatedColumnSize: 100,
estimatedRowSize: 30,
noContentRenderer: function() {
return null;
},
onScroll: function() {
return null;
},
onSectionRendered: function() {
return null;
},
overscanColumnCount: 0,
overscanRowCount: 10,
scrollToAlignment: "auto",
style: {},
tabIndex: 0
}, exports["default"] = Grid;
}, /* 186 */
/***/
function(module, exports) {
"use strict";
function calculateSizeAndPositionDataAndUpdateScrollOffset(_ref) {
var cellCount = _ref.cellCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex;
cellCount === nextCellsCount && ("number" != typeof cellSize && "number" != typeof nextCellSize || cellSize === nextCellSize) || (computeMetadataCallback(computeMetadataCallbackProps),
scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex());
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = calculateSizeAndPositionDataAndUpdateScrollOffset;
}, /* 187 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]);
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.DEFAULT_MAX_SCROLL_SIZE = void 0;
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _CellSizeAndPositionManager = __webpack_require__(188), _CellSizeAndPositionManager2 = _interopRequireDefault(_CellSizeAndPositionManager), DEFAULT_MAX_SCROLL_SIZE = exports.DEFAULT_MAX_SCROLL_SIZE = 1e7, ScalingCellSizeAndPositionManager = function() {
function ScalingCellSizeAndPositionManager(_ref) {
var _ref$maxScrollSize = _ref.maxScrollSize, maxScrollSize = void 0 === _ref$maxScrollSize ? DEFAULT_MAX_SCROLL_SIZE : _ref$maxScrollSize, params = _objectWithoutProperties(_ref, [ "maxScrollSize" ]);
_classCallCheck(this, ScalingCellSizeAndPositionManager), this._cellSizeAndPositionManager = new _CellSizeAndPositionManager2["default"](params),
this._maxScrollSize = maxScrollSize;
}
return _createClass(ScalingCellSizeAndPositionManager, [ {
key: "configure",
value: function(params) {
this._cellSizeAndPositionManager.configure(params);
}
}, {
key: "getCellCount",
value: function() {
return this._cellSizeAndPositionManager.getCellCount();
}
}, {
key: "getEstimatedCellSize",
value: function() {
return this._cellSizeAndPositionManager.getEstimatedCellSize();
}
}, {
key: "getLastMeasuredIndex",
value: function() {
return this._cellSizeAndPositionManager.getLastMeasuredIndex();
}
}, {
key: "getOffsetAdjustment",
value: function(_ref2) {
var containerSize = _ref2.containerSize, offset = _ref2.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(), offsetPercentage = this._getOffsetPercentage({
containerSize: containerSize,
offset: offset,
totalSize: safeTotalSize
});
return Math.round(offsetPercentage * (safeTotalSize - totalSize));
}
}, {
key: "getSizeAndPositionOfCell",
value: function(index) {
return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index);
}
}, {
key: "getSizeAndPositionOfLastMeasuredCell",
value: function() {
return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell();
}
}, {
key: "getTotalSize",
value: function() {
return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize());
}
}, {
key: "getUpdatedOffsetForIndex",
value: function(_ref3) {
var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex;
currentOffset = this._safeOffsetToOffset({
containerSize: containerSize,
offset: currentOffset
});
var offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({
align: align,
containerSize: containerSize,
currentOffset: currentOffset,
targetIndex: targetIndex
});
return this._offsetToSafeOffset({
containerSize: containerSize,
offset: offset
});
}
}, {
key: "getVisibleCellRange",
value: function(_ref4) {
var containerSize = _ref4.containerSize, offset = _ref4.offset;
return offset = this._safeOffsetToOffset({
containerSize: containerSize,
offset: offset
}), this._cellSizeAndPositionManager.getVisibleCellRange({
containerSize: containerSize,
offset: offset
});
}
}, {
key: "resetCell",
value: function(index) {
this._cellSizeAndPositionManager.resetCell(index);
}
}, {
key: "_getOffsetPercentage",
value: function(_ref5) {
var containerSize = _ref5.containerSize, offset = _ref5.offset, totalSize = _ref5.totalSize;
return containerSize >= totalSize ? 0 : offset / (totalSize - containerSize);
}
}, {
key: "_offsetToSafeOffset",
value: function(_ref6) {
var containerSize = _ref6.containerSize, offset = _ref6.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize();
if (totalSize === safeTotalSize) return offset;
var offsetPercentage = this._getOffsetPercentage({
containerSize: containerSize,
offset: offset,
totalSize: totalSize
});
return Math.round(offsetPercentage * (safeTotalSize - containerSize));
}
}, {
key: "_safeOffsetToOffset",
value: function(_ref7) {
var containerSize = _ref7.containerSize, offset = _ref7.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize();
if (totalSize === safeTotalSize) return offset;
var offsetPercentage = this._getOffsetPercentage({
containerSize: containerSize,
offset: offset,
totalSize: safeTotalSize
});
return Math.round(offsetPercentage * (totalSize - containerSize));
}
} ]), ScalingCellSizeAndPositionManager;
}();
exports["default"] = ScalingCellSizeAndPositionManager;
}, /* 188 */
/***/
function(module, exports) {
"use strict";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), CellSizeAndPositionManager = function() {
function CellSizeAndPositionManager(_ref) {
var cellCount = _ref.cellCount, cellSizeGetter = _ref.cellSizeGetter, estimatedCellSize = _ref.estimatedCellSize;
_classCallCheck(this, CellSizeAndPositionManager), this._cellSizeGetter = cellSizeGetter,
this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize, this._cellSizeAndPositionData = {},
this._lastMeasuredIndex = -1;
}
return _createClass(CellSizeAndPositionManager, [ {
key: "configure",
value: function(_ref2) {
var cellCount = _ref2.cellCount, estimatedCellSize = _ref2.estimatedCellSize;
this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize;
}
}, {
key: "getCellCount",
value: function() {
return this._cellCount;
}
}, {
key: "getEstimatedCellSize",
value: function() {
return this._estimatedCellSize;
}
}, {
key: "getLastMeasuredIndex",
value: function() {
return this._lastMeasuredIndex;
}
}, {
key: "getSizeAndPositionOfCell",
value: function(index) {
if (0 > index || index >= this._cellCount) throw Error("Requested index " + index + " is outside of range 0.." + this._cellCount);
if (index > this._lastMeasuredIndex) {
for (var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), _offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size, i = this._lastMeasuredIndex + 1; index >= i; i++) {
var _size = this._cellSizeGetter({
index: i
});
if (null == _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size);
this._cellSizeAndPositionData[i] = {
offset: _offset,
size: _size
}, _offset += _size;
}
this._lastMeasuredIndex = index;
}
return this._cellSizeAndPositionData[index];
}
}, {
key: "getSizeAndPositionOfLastMeasuredCell",
value: function() {
return this._lastMeasuredIndex >= 0 ? this._cellSizeAndPositionData[this._lastMeasuredIndex] : {
offset: 0,
size: 0
};
}
}, {
key: "getTotalSize",
value: function() {
var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell();
return lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size + (this._cellCount - this._lastMeasuredIndex - 1) * this._estimatedCellSize;
}
}, {
key: "getUpdatedOffsetForIndex",
value: function(_ref3) {
var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex, datum = this.getSizeAndPositionOfCell(targetIndex), maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size;
switch (align) {
case "start":
return maxOffset;
case "end":
return minOffset;
case "center":
return maxOffset - (containerSize + datum.size) / 2;
default:
return Math.max(minOffset, Math.min(maxOffset, currentOffset));
}
}
}, {
key: "getVisibleCellRange",
value: function(_ref4) {
var containerSize = _ref4.containerSize, offset = _ref4.offset, totalSize = this.getTotalSize();
if (0 === totalSize) return {};
var maxOffset = offset + containerSize, start = this._findNearestCell(offset), datum = this.getSizeAndPositionOfCell(start);
offset = datum.offset + datum.size;
for (var stop = start; maxOffset > offset && stop < this._cellCount - 1; ) stop++,
offset += this.getSizeAndPositionOfCell(stop).size;
return {
start: start,
stop: stop
};
}
}, {
key: "resetCell",
value: function(index) {
this._lastMeasuredIndex = index - 1;
}
}, {
key: "_binarySearch",
value: function(_ref5) {
for (var high = _ref5.high, low = _ref5.low, offset = _ref5.offset, middle = void 0, currentOffset = void 0; high >= low; ) {
if (middle = low + Math.floor((high - low) / 2), currentOffset = this.getSizeAndPositionOfCell(middle).offset,
currentOffset === offset) return middle;
offset > currentOffset ? low = middle + 1 : currentOffset > offset && (high = middle - 1);
}
return low > 0 ? low - 1 : void 0;
}
}, {
key: "_exponentialSearch",
value: function(_ref6) {
for (var index = _ref6.index, offset = _ref6.offset, interval = 1; index < this._cellCount && this.getSizeAndPositionOfCell(index).offset < offset; ) index += interval,
interval *= 2;
return this._binarySearch({
high: Math.min(index, this._cellCount - 1),
low: Math.floor(index / 2),
offset: offset
});
}
}, {
key: "_findNearestCell",
value: function(offset) {
if (isNaN(offset)) throw Error("Invalid offset " + offset + " specified");
offset = Math.max(0, offset);
var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex);
return lastMeasuredCellSizeAndPosition.offset >= offset ? this._binarySearch({
high: lastMeasuredIndex,
low: 0,
offset: offset
}) : this._exponentialSearch({
index: lastMeasuredIndex,
offset: offset
});
}
} ]), CellSizeAndPositionManager;
}();
exports["default"] = CellSizeAndPositionManager;
}, /* 189 */
/***/
function(module, exports) {
"use strict";
function getOverscanIndices(_ref) {
var cellCount = _ref.cellCount, overscanCellsCount = _ref.overscanCellsCount, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex;
return {
overscanStartIndex: Math.max(0, startIndex - overscanCellsCount),
overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount)
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = getOverscanIndices;
}, /* 190 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function updateScrollIndexHelper(_ref) {
var cellSize = _ref.cellSize, cellSizeAndPositionManager = _ref.cellSizeAndPositionManager, previousCellsCount = _ref.previousCellsCount, previousCellSize = _ref.previousCellSize, previousScrollToAlignment = _ref.previousScrollToAlignment, previousScrollToIndex = _ref.previousScrollToIndex, previousSize = _ref.previousSize, scrollOffset = _ref.scrollOffset, scrollToAlignment = _ref.scrollToAlignment, scrollToIndex = _ref.scrollToIndex, size = _ref.size, updateScrollIndexCallback = _ref.updateScrollIndexCallback, cellCount = cellSizeAndPositionManager.getCellCount(), hasScrollToIndex = scrollToIndex >= 0 && cellCount > scrollToIndex, sizeHasChanged = size !== previousSize || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize;
if (hasScrollToIndex && (sizeHasChanged || scrollToAlignment !== previousScrollToAlignment || scrollToIndex !== previousScrollToIndex)) updateScrollIndexCallback(scrollToIndex); else if (!hasScrollToIndex && cellCount > 0 && (previousSize > size || previousCellsCount > cellCount)) {
scrollToIndex = cellCount - 1;
var cellMetadatum = cellSizeAndPositionManager.getSizeAndPositionOfCell(scrollToIndex), calculatedScrollOffset = (0,
_getUpdatedOffsetForIndex2["default"])({
cellOffset: cellMetadatum.offset,
cellSize: cellMetadatum.size,
containerSize: size,
currentOffset: scrollOffset
});
scrollOffset > calculatedScrollOffset && updateScrollIndexCallback(cellCount - 1);
}
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = updateScrollIndexHelper;
var _getUpdatedOffsetForIndex = __webpack_require__(181), _getUpdatedOffsetForIndex2 = _interopRequireDefault(_getUpdatedOffsetForIndex);
}, /* 191 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function defaultCellRangeRenderer(_ref) {
for (var cellCache = _ref.cellCache, cellClassName = _ref.cellClassName, cellRenderer = _ref.cellRenderer, cellStyle = _ref.cellStyle, columnSizeAndPositionManager = _ref.columnSizeAndPositionManager, columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, horizontalOffsetAdjustment = _ref.horizontalOffsetAdjustment, isScrolling = _ref.isScrolling, rowSizeAndPositionManager = _ref.rowSizeAndPositionManager, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex, verticalOffsetAdjustment = (_ref.scrollLeft,
_ref.scrollTop, _ref.verticalOffsetAdjustment), renderedCells = [], rowIndex = rowStartIndex; rowStopIndex >= rowIndex; rowIndex++) for (var rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex), columnIndex = columnStartIndex; columnStopIndex >= columnIndex; columnIndex++) {
var columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex), key = rowIndex + "-" + columnIndex, cellStyleObject = cellStyle({
rowIndex: rowIndex,
columnIndex: columnIndex
}), renderedCell = void 0;
if (isScrolling ? (cellCache[key] || (cellCache[key] = cellRenderer({
columnIndex: columnIndex,
isScrolling: isScrolling,
rowIndex: rowIndex
})), renderedCell = cellCache[key]) : renderedCell = cellRenderer({
columnIndex: columnIndex,
isScrolling: isScrolling,
rowIndex: rowIndex
}), null != renderedCell && renderedCell !== !1) {
var className = cellClassName({
columnIndex: columnIndex,
rowIndex: rowIndex
}), child = _react2["default"].createElement("div", {
key: key,
className: (0, _classnames2["default"])("Grid__cell", className),
style: _extends({
height: rowDatum.size,
left: columnDatum.offset + horizontalOffsetAdjustment,
top: rowDatum.offset + verticalOffsetAdjustment,
width: columnDatum.size
}, cellStyleObject)
}, renderedCell);
renderedCells.push(child);
}
}
return renderedCells;
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
};
exports["default"] = defaultCellRangeRenderer;
var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames);
}, /* 192 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.SortIndicator = exports.SortDirection = exports.FlexColumn = exports.FlexTable = exports["default"] = void 0;
var _FlexTable2 = __webpack_require__(193), _FlexTable3 = _interopRequireDefault(_FlexTable2), _FlexColumn2 = __webpack_require__(194), _FlexColumn3 = _interopRequireDefault(_FlexColumn2), _SortDirection2 = __webpack_require__(197), _SortDirection3 = _interopRequireDefault(_SortDirection2), _SortIndicator2 = __webpack_require__(196), _SortIndicator3 = _interopRequireDefault(_SortIndicator2);
exports["default"] = _FlexTable3["default"], exports.FlexTable = _FlexTable3["default"],
exports.FlexColumn = _FlexColumn3["default"], exports.SortDirection = _SortDirection3["default"],
exports.SortIndicator = _SortIndicator3["default"];
}, /* 193 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}, _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _FlexColumn = __webpack_require__(194), _FlexColumn2 = _interopRequireDefault(_FlexColumn), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _Grid = __webpack_require__(184), _Grid2 = _interopRequireDefault(_Grid), _SortDirection = __webpack_require__(197), _SortDirection2 = _interopRequireDefault(_SortDirection), FlexTable = function(_Component) {
function FlexTable(props) {
_classCallCheck(this, FlexTable);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(FlexTable).call(this, props));
return _this.state = {
scrollbarWidth: 0
}, _this._cellClassName = _this._cellClassName.bind(_this), _this._cellStyle = _this._cellStyle.bind(_this),
_this._createRow = _this._createRow.bind(_this), _this._onScroll = _this._onScroll.bind(_this),
_this._onSectionRendered = _this._onSectionRendered.bind(_this), _this;
}
return _inherits(FlexTable, _Component), _createClass(FlexTable, [ {
key: "forceUpdateGrid",
value: function() {
this.refs.Grid.forceUpdate();
}
}, {
key: "measureAllRows",
value: function() {
this.refs.Grid.measureAllCells();
}
}, {
key: "recomputeRowHeights",
value: function() {
var index = arguments.length <= 0 || void 0 === arguments[0] ? 0 : arguments[0];
this.refs.Grid.recomputeGridSize({
rowIndex: index
}), this.forceUpdateGrid();
}
}, {
key: "componentDidMount",
value: function() {
this._setScrollbarWidth();
}
}, {
key: "componentDidUpdate",
value: function() {
this._setScrollbarWidth();
}
}, {
key: "render",
value: function() {
var _this2 = this, _props = this.props, children = _props.children, className = _props.className, disableHeader = _props.disableHeader, gridClassName = _props.gridClassName, gridStyle = _props.gridStyle, headerHeight = _props.headerHeight, height = _props.height, noRowsRenderer = _props.noRowsRenderer, rowClassName = _props.rowClassName, rowStyle = _props.rowStyle, scrollToIndex = _props.scrollToIndex, style = _props.style, width = _props.width, scrollbarWidth = this.state.scrollbarWidth, availableRowsHeight = height - headerHeight, rowClass = rowClassName instanceof Function ? rowClassName({
index: -1
}) : rowClassName;
return this._cachedColumnStyles = [], _react2["default"].Children.toArray(children).forEach(function(column, index) {
_this2._cachedColumnStyles[index] = _this2._getFlexStyleForColumn(column, column.props.style);
}), _react2["default"].createElement("div", {
className: (0, _classnames2["default"])("FlexTable", className),
style: style
}, !disableHeader && _react2["default"].createElement("div", {
className: (0, _classnames2["default"])("FlexTable__headerRow", rowClass),
style: _extends({}, rowStyle, {
height: headerHeight,
paddingRight: scrollbarWidth,
width: width
})
}, this._getRenderedHeaderRow()), _react2["default"].createElement(_Grid2["default"], _extends({}, this.props, {
className: (0, _classnames2["default"])("FlexTable__Grid", gridClassName),
cellClassName: this._cellClassName,
cellRenderer: this._createRow,
cellStyle: this._cellStyle,
columnWidth: width,
columnCount: 1,
height: availableRowsHeight,
noContentRenderer: noRowsRenderer,
onScroll: this._onScroll,
onSectionRendered: this._onSectionRendered,
ref: "Grid",
scrollbarWidth: scrollbarWidth,
scrollToRow: scrollToIndex,
style: gridStyle
})));
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_cellClassName",
value: function(_ref) {
var rowIndex = _ref.rowIndex, rowWrapperClassName = this.props.rowWrapperClassName;
return rowWrapperClassName instanceof Function ? rowWrapperClassName({
index: rowIndex - 1
}) : rowWrapperClassName;
}
}, {
key: "_cellStyle",
value: function(_ref2) {
var rowIndex = _ref2.rowIndex, rowWrapperStyle = this.props.rowWrapperStyle;
return rowWrapperStyle instanceof Function ? rowWrapperStyle({
index: rowIndex - 1
}) : rowWrapperStyle;
}
}, {
key: "_createColumn",
value: function(_ref3) {
var column = _ref3.column, columnIndex = _ref3.columnIndex, isScrolling = _ref3.isScrolling, rowData = _ref3.rowData, rowIndex = _ref3.rowIndex, _column$props = column.props, cellDataGetter = _column$props.cellDataGetter, cellRenderer = _column$props.cellRenderer, className = _column$props.className, columnData = _column$props.columnData, dataKey = _column$props.dataKey, cellData = cellDataGetter({
columnData: columnData,
dataKey: dataKey,
rowData: rowData
}), renderedCell = cellRenderer({
cellData: cellData,
columnData: columnData,
dataKey: dataKey,
isScrolling: isScrolling,
rowData: rowData,
rowIndex: rowIndex
}), style = this._cachedColumnStyles[columnIndex], title = "string" == typeof renderedCell ? renderedCell : null;
return _react2["default"].createElement("div", {
key: "Row" + rowIndex + "-Col" + columnIndex,
className: (0, _classnames2["default"])("FlexTable__rowColumn", className),
style: style,
title: title
}, renderedCell);
}
}, {
key: "_createHeader",
value: function(column, columnIndex) {
var _props2 = this.props, headerClassName = _props2.headerClassName, headerStyle = _props2.headerStyle, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, headerRenderer = _column$props2.headerRenderer, label = _column$props2.label, columnData = _column$props2.columnData, sortEnabled = !disableSort && sort, classNames = (0,
_classnames2["default"])("FlexTable__headerColumn", headerClassName, column.props.headerClassName, {
FlexTable__sortableHeaderColumn: sortEnabled
}), style = this._getFlexStyleForColumn(column, headerStyle), renderedHeader = headerRenderer({
columnData: columnData,
dataKey: dataKey,
disableSort: disableSort,
label: label,
sortBy: sortBy,
sortDirection: sortDirection
}), a11yProps = {};
return (sortEnabled || onHeaderClick) && !function() {
var newSortDirection = sortBy !== dataKey || sortDirection === _SortDirection2["default"].DESC ? _SortDirection2["default"].ASC : _SortDirection2["default"].DESC, onClick = function() {
sortEnabled && sort({
sortBy: dataKey,
sortDirection: newSortDirection
}), onHeaderClick && onHeaderClick({
columnData: columnData,
dataKey: dataKey
});
}, onKeyDown = function(event) {
"Enter" !== event.key && " " !== event.key || onClick();
};
a11yProps["aria-label"] = column.props["aria-label"] || label || dataKey, a11yProps.role = "rowheader",
a11yProps.tabIndex = 0, a11yProps.onClick = onClick, a11yProps.onKeyDown = onKeyDown;
}(), _react2["default"].createElement("div", _extends({}, a11yProps, {
key: "Header-Col" + columnIndex,
className: classNames,
style: style
}), renderedHeader);
}
}, {
key: "_createRow",
value: function(_ref4) {
var _this3 = this, index = _ref4.rowIndex, isScrolling = _ref4.isScrolling, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, onRowMouseOver = _props3.onRowMouseOver, onRowMouseOut = _props3.onRowMouseOut, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, rowStyle = _props3.rowStyle, scrollbarWidth = this.state.scrollbarWidth, rowClass = rowClassName instanceof Function ? rowClassName({
index: index
}) : rowClassName, rowData = rowGetter({
index: index
}), renderedRow = _react2["default"].Children.toArray(children).map(function(column, columnIndex) {
return _this3._createColumn({
column: column,
columnIndex: columnIndex,
isScrolling: isScrolling,
rowData: rowData,
rowIndex: index
});
}), a11yProps = {};
return (onRowClick || onRowMouseOver || onRowMouseOut) && (a11yProps["aria-label"] = "row",
a11yProps.role = "row", a11yProps.tabIndex = 0, onRowClick && (a11yProps.onClick = function() {
return onRowClick({
index: index
});
}), onRowMouseOut && (a11yProps.onMouseOut = function() {
return onRowMouseOut({
index: index
});
}), onRowMouseOver && (a11yProps.onMouseOver = function() {
return onRowMouseOver({
index: index
});
})), _react2["default"].createElement("div", _extends({}, a11yProps, {
key: index,
className: (0, _classnames2["default"])("FlexTable__row", rowClass),
style: _extends({}, rowStyle, {
height: this._getRowHeight(index),
paddingRight: scrollbarWidth
})
}), renderedRow);
}
}, {
key: "_getFlexStyleForColumn",
value: function(column) {
var customStyle = arguments.length <= 1 || void 0 === arguments[1] ? {} : arguments[1], flexValue = column.props.flexGrow + " " + column.props.flexShrink + " " + column.props.width + "px", style = _extends({}, customStyle, {
flex: flexValue,
msFlex: flexValue,
WebkitFlex: flexValue
});
return column.props.maxWidth && (style.maxWidth = column.props.maxWidth), column.props.minWidth && (style.minWidth = column.props.minWidth),
style;
}
}, {
key: "_getRenderedHeaderRow",
value: function() {
var _this4 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : _react2["default"].Children.toArray(children);
return items.map(function(column, index) {
return _this4._createHeader(column, index);
});
}
}, {
key: "_getRowHeight",
value: function(rowIndex) {
var rowHeight = this.props.rowHeight;
return rowHeight instanceof Function ? rowHeight({
index: rowIndex
}) : rowHeight;
}
}, {
key: "_onScroll",
value: function(_ref5) {
var clientHeight = _ref5.clientHeight, scrollHeight = _ref5.scrollHeight, scrollTop = _ref5.scrollTop, onScroll = this.props.onScroll;
onScroll({
clientHeight: clientHeight,
scrollHeight: scrollHeight,
scrollTop: scrollTop
});
}
}, {
key: "_onSectionRendered",
value: function(_ref6) {
var rowOverscanStartIndex = _ref6.rowOverscanStartIndex, rowOverscanStopIndex = _ref6.rowOverscanStopIndex, rowStartIndex = _ref6.rowStartIndex, rowStopIndex = _ref6.rowStopIndex, onRowsRendered = this.props.onRowsRendered;
onRowsRendered({
overscanStartIndex: rowOverscanStartIndex,
overscanStopIndex: rowOverscanStopIndex,
startIndex: rowStartIndex,
stopIndex: rowStopIndex
});
}
}, {
key: "_setScrollbarWidth",
value: function() {
var Grid = (0, _reactDom.findDOMNode)(this.refs.Grid), clientWidth = Grid.clientWidth || 0, offsetWidth = Grid.offsetWidth || 0, scrollbarWidth = offsetWidth - clientWidth;
this.setState({
scrollbarWidth: scrollbarWidth
});
}
} ]), FlexTable;
}(_react.Component);
FlexTable.propTypes = {
"aria-label": _react.PropTypes.string,
autoHeight: _react.PropTypes.bool,
children: function children(props, propName, componentName) {
for (var children = _react2["default"].Children.toArray(props.children), i = 0; i < children.length; i++) if (children[i].type !== _FlexColumn2["default"]) return new Error("FlexTable only accepts children of type FlexColumn");
},
className: _react.PropTypes.string,
disableHeader: _react.PropTypes.bool,
estimatedRowSize: _react.PropTypes.number.isRequired,
gridClassName: _react.PropTypes.string,
gridStyle: _react.PropTypes.object,
headerClassName: _react.PropTypes.string,
headerHeight: _react.PropTypes.number.isRequired,
height: _react.PropTypes.number.isRequired,
noRowsRenderer: _react.PropTypes.func,
onHeaderClick: _react.PropTypes.func,
headerStyle: _react.PropTypes.object,
onRowClick: _react.PropTypes.func,
onRowMouseOut: _react.PropTypes.func,
onRowMouseOver: _react.PropTypes.func,
onRowsRendered: _react.PropTypes.func,
onScroll: _react.PropTypes.func.isRequired,
overscanRowCount: _react.PropTypes.number.isRequired,
rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]),
rowGetter: _react.PropTypes.func.isRequired,
rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired,
rowCount: _react.PropTypes.number.isRequired,
rowStyle: _react.PropTypes.object,
rowWrapperClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]),
rowWrapperStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]),
scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired,
scrollToIndex: _react.PropTypes.number,
scrollTop: _react.PropTypes.number,
sort: _react.PropTypes.func,
sortBy: _react.PropTypes.string,
sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ]),
style: _react.PropTypes.object,
tabIndex: _react.PropTypes.number,
width: _react.PropTypes.number.isRequired
}, FlexTable.defaultProps = {
disableHeader: !1,
estimatedRowSize: 30,
headerHeight: 0,
headerStyle: {},
noRowsRenderer: function() {
return null;
},
onRowsRendered: function() {
return null;
},
onScroll: function() {
return null;
},
overscanRowCount: 10,
rowStyle: {},
scrollToAlignment: "auto",
style: {}
}, exports["default"] = FlexTable;
}, /* 194 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _react = __webpack_require__(3), _defaultHeaderRenderer = __webpack_require__(195), _defaultHeaderRenderer2 = _interopRequireDefault(_defaultHeaderRenderer), _defaultCellRenderer = __webpack_require__(198), _defaultCellRenderer2 = _interopRequireDefault(_defaultCellRenderer), _defaultCellDataGetter = __webpack_require__(199), _defaultCellDataGetter2 = _interopRequireDefault(_defaultCellDataGetter), Column = function(_Component) {
function Column() {
return _classCallCheck(this, Column), _possibleConstructorReturn(this, Object.getPrototypeOf(Column).apply(this, arguments));
}
return _inherits(Column, _Component), Column;
}(_react.Component);
Column.defaultProps = {
cellDataGetter: _defaultCellDataGetter2["default"],
cellRenderer: _defaultCellRenderer2["default"],
cellStyle: {},
flexGrow: 0,
flexShrink: 1,
headerRenderer: _defaultHeaderRenderer2["default"]
}, Column.propTypes = {
"aria-label": _react.PropTypes.string,
cellDataGetter: _react.PropTypes.func,
cellRenderer: _react.PropTypes.func,
className: _react.PropTypes.string,
columnData: _react.PropTypes.object,
dataKey: _react.PropTypes.any.isRequired,
disableSort: _react.PropTypes.bool,
flexGrow: _react.PropTypes.number,
flexShrink: _react.PropTypes.number,
headerClassName: _react.PropTypes.string,
headerRenderer: _react.PropTypes.func.isRequired,
label: _react.PropTypes.string,
maxWidth: _react.PropTypes.number,
minWidth: _react.PropTypes.number,
style: _react.PropTypes.object,
width: _react.PropTypes.number.isRequired
}, exports["default"] = Column;
}, /* 195 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function defaultHeaderRenderer(_ref) {
var dataKey = (_ref.columnData, _ref.dataKey), label = (_ref.disableSort, _ref.label), sortBy = _ref.sortBy, sortDirection = _ref.sortDirection, showSortIndicator = sortBy === dataKey, children = [ _react2["default"].createElement("span", {
className: "FlexTable__headerTruncatedText",
key: "label",
title: label
}, label) ];
return showSortIndicator && children.push(_react2["default"].createElement(_SortIndicator2["default"], {
key: "SortIndicator",
sortDirection: sortDirection
})), children;
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = defaultHeaderRenderer;
var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _SortIndicator = __webpack_require__(196), _SortIndicator2 = _interopRequireDefault(_SortIndicator);
}, /* 196 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function SortIndicator(_ref) {
var sortDirection = _ref.sortDirection, classNames = (0, _classnames2["default"])("FlexTable__sortableHeaderIcon", {
"FlexTable__sortableHeaderIcon--ASC": sortDirection === _SortDirection2["default"].ASC,
"FlexTable__sortableHeaderIcon--DESC": sortDirection === _SortDirection2["default"].DESC
});
return _react2["default"].createElement("svg", {
className: classNames,
width: 18,
height: 18,
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, sortDirection === _SortDirection2["default"].ASC ? _react2["default"].createElement("path", {
d: "M7 14l5-5 5 5z"
}) : _react2["default"].createElement("path", {
d: "M7 10l5 5 5-5z"
}), _react2["default"].createElement("path", {
d: "M0 0h24v24H0z",
fill: "none"
}));
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = SortIndicator;
var _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _SortDirection = __webpack_require__(197), _SortDirection2 = _interopRequireDefault(_SortDirection);
SortIndicator.propTypes = {
sortDirection: _react.PropTypes.oneOf([ _SortDirection2["default"].ASC, _SortDirection2["default"].DESC ])
};
}, /* 197 */
/***/
function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
});
var SortDirection = {
ASC: "ASC",
DESC: "DESC"
};
exports["default"] = SortDirection;
}, /* 198 */
/***/
function(module, exports) {
"use strict";
function defaultCellRenderer(_ref) {
var cellData = _ref.cellData;
_ref.cellDataKey, _ref.columnData, _ref.rowData, _ref.rowIndex;
return null == cellData ? "" : String(cellData);
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = defaultCellRenderer;
}, /* 199 */
/***/
function(module, exports) {
"use strict";
function defaultCellDataGetter(_ref) {
var dataKey = (_ref.columnData, _ref.dataKey), rowData = _ref.rowData;
return rowData.get instanceof Function ? rowData.get(dataKey) : rowData[dataKey];
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports["default"] = defaultCellDataGetter;
}, /* 200 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.InfiniteLoader = exports["default"] = void 0;
var _InfiniteLoader2 = __webpack_require__(201), _InfiniteLoader3 = _interopRequireDefault(_InfiniteLoader2);
exports["default"] = _InfiniteLoader3["default"], exports.InfiniteLoader = _InfiniteLoader3["default"];
}, /* 201 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
function isRangeVisible(_ref2) {
var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex;
return !(startIndex > lastRenderedStopIndex || lastRenderedStartIndex > stopIndex);
}
function scanForUnloadedRanges(_ref3) {
for (var isRowLoaded = _ref3.isRowLoaded, minimumBatchSize = _ref3.minimumBatchSize, rowCount = _ref3.rowCount, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, index = startIndex; stopIndex >= index; index++) {
var loaded = isRowLoaded({
index: index
});
loaded ? null !== rangeStopIndex && (unloadedRanges.push({
startIndex: rangeStartIndex,
stopIndex: rangeStopIndex
}), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = index, null === rangeStartIndex && (rangeStartIndex = index));
}
if (null !== rangeStopIndex) {
for (var potentialStopIndex = Math.min(Math.max(rangeStopIndex, rangeStartIndex + minimumBatchSize - 1), rowCount - 1), _index = rangeStopIndex + 1; potentialStopIndex >= _index && !isRowLoaded({
index: _index
}); _index++) rangeStopIndex = _index;
unloadedRanges.push({
startIndex: rangeStartIndex,
stopIndex: rangeStopIndex
});
}
if (unloadedRanges.length) for (var firstUnloadedRange = unloadedRanges[0]; firstUnloadedRange.stopIndex - firstUnloadedRange.startIndex + 1 < minimumBatchSize && firstUnloadedRange.startIndex > 0; ) {
var _index2 = firstUnloadedRange.startIndex - 1;
if (isRowLoaded({
index: _index2
})) break;
firstUnloadedRange.startIndex = _index2;
}
return unloadedRanges;
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}();
exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges;
var _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), InfiniteLoader = function(_Component) {
function InfiniteLoader(props, context) {
_classCallCheck(this, InfiniteLoader);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(InfiniteLoader).call(this, props, context));
return _this._onRowsRendered = _this._onRowsRendered.bind(_this), _this._registerChild = _this._registerChild.bind(_this),
_this;
}
return _inherits(InfiniteLoader, _Component), _createClass(InfiniteLoader, [ {
key: "render",
value: function() {
var children = this.props.children;
return children({
onRowsRendered: this._onRowsRendered,
registerChild: this._registerChild
});
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_onRowsRendered",
value: function(_ref) {
var _this2 = this, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, _props = this.props, isRowLoaded = _props.isRowLoaded, loadMoreRows = _props.loadMoreRows, minimumBatchSize = _props.minimumBatchSize, rowCount = _props.rowCount, threshold = _props.threshold;
this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex;
var unloadedRanges = scanForUnloadedRanges({
isRowLoaded: isRowLoaded,
minimumBatchSize: minimumBatchSize,
rowCount: rowCount,
startIndex: Math.max(0, startIndex - threshold),
stopIndex: Math.min(rowCount - 1, stopIndex + threshold)
});
unloadedRanges.forEach(function(unloadedRange) {
var promise = loadMoreRows(unloadedRange);
promise && promise.then(function() {
isRangeVisible({
lastRenderedStartIndex: _this2._lastRenderedStartIndex,
lastRenderedStopIndex: _this2._lastRenderedStopIndex,
startIndex: unloadedRange.startIndex,
stopIndex: unloadedRange.stopIndex
}) && _this2._registeredChild && _this2._registeredChild.forceUpdate();
});
});
}
}, {
key: "_registerChild",
value: function(registeredChild) {
this._registeredChild = registeredChild;
}
} ]), InfiniteLoader;
}(_react.Component);
InfiniteLoader.propTypes = {
children: _react.PropTypes.func.isRequired,
isRowLoaded: _react.PropTypes.func.isRequired,
loadMoreRows: _react.PropTypes.func.isRequired,
minimumBatchSize: _react.PropTypes.number.isRequired,
rowCount: _react.PropTypes.number.isRequired,
threshold: _react.PropTypes.number.isRequired
}, InfiniteLoader.defaultProps = {
minimumBatchSize: 10,
rowCount: 0,
threshold: 15
}, exports["default"] = InfiniteLoader;
}, /* 202 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.ScrollSync = exports["default"] = void 0;
var _ScrollSync2 = __webpack_require__(203), _ScrollSync3 = _interopRequireDefault(_ScrollSync2);
exports["default"] = _ScrollSync3["default"], exports.ScrollSync = _ScrollSync3["default"];
}, /* 203 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), ScrollSync = function(_Component) {
function ScrollSync(props, context) {
_classCallCheck(this, ScrollSync);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ScrollSync).call(this, props, context));
return _this.state = {
clientHeight: 0,
clientWidth: 0,
scrollHeight: 0,
scrollLeft: 0,
scrollTop: 0,
scrollWidth: 0
}, _this._onScroll = _this._onScroll.bind(_this), _this;
}
return _inherits(ScrollSync, _Component), _createClass(ScrollSync, [ {
key: "render",
value: function() {
var children = this.props.children, _state = this.state, clientHeight = _state.clientHeight, clientWidth = _state.clientWidth, scrollHeight = _state.scrollHeight, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop, scrollWidth = _state.scrollWidth;
return children({
clientHeight: clientHeight,
clientWidth: clientWidth,
onScroll: this._onScroll,
scrollHeight: scrollHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: scrollWidth
});
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_onScroll",
value: function(_ref) {
var clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth, scrollHeight = _ref.scrollHeight, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, scrollWidth = _ref.scrollWidth;
this.setState({
clientHeight: clientHeight,
clientWidth: clientWidth,
scrollHeight: scrollHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: scrollWidth
});
}
} ]), ScrollSync;
}(_react.Component);
ScrollSync.propTypes = {
children: _react.PropTypes.func.isRequired
}, exports["default"] = ScrollSync;
}, /* 204 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.VirtualScroll = exports["default"] = void 0;
var _VirtualScroll2 = __webpack_require__(205), _VirtualScroll3 = _interopRequireDefault(_VirtualScroll2);
exports["default"] = _VirtualScroll3["default"], exports.VirtualScroll = _VirtualScroll3["default"];
}, /* 205 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}, _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _Grid = __webpack_require__(184), _Grid2 = _interopRequireDefault(_Grid), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(172), _classnames2 = _interopRequireDefault(_classnames), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), VirtualScroll = function(_Component) {
function VirtualScroll(props, context) {
_classCallCheck(this, VirtualScroll);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(VirtualScroll).call(this, props, context));
return _this._cellRenderer = _this._cellRenderer.bind(_this), _this._createRowClassNameGetter = _this._createRowClassNameGetter.bind(_this),
_this._createRowStyleGetter = _this._createRowStyleGetter.bind(_this), _this._onScroll = _this._onScroll.bind(_this),
_this._onSectionRendered = _this._onSectionRendered.bind(_this), _this;
}
return _inherits(VirtualScroll, _Component), _createClass(VirtualScroll, [ {
key: "forceUpdateGrid",
value: function() {
this.refs.Grid.forceUpdate();
}
}, {
key: "measureAllRows",
value: function() {
this.refs.Grid.measureAllCells();
}
}, {
key: "recomputeRowHeights",
value: function() {
var index = arguments.length <= 0 || void 0 === arguments[0] ? 0 : arguments[0];
this.refs.Grid.recomputeGridSize({
rowIndex: index
}), this.forceUpdateGrid();
}
}, {
key: "render",
value: function() {
var _props = this.props, autoHeight = _props.autoHeight, className = _props.className, estimatedRowSize = _props.estimatedRowSize, height = _props.height, noRowsRenderer = _props.noRowsRenderer, rowHeight = _props.rowHeight, overscanRowCount = _props.overscanRowCount, rowCount = _props.rowCount, scrollToAlignment = _props.scrollToAlignment, scrollToIndex = _props.scrollToIndex, scrollTop = _props.scrollTop, style = _props.style, tabIndex = _props.tabIndex, width = _props.width, classNames = (0,
_classnames2["default"])("VirtualScroll", className);
return _react2["default"].createElement(_Grid2["default"], {
autoHeight: autoHeight,
"aria-label": this.props["aria-label"],
className: classNames,
cellRenderer: this._cellRenderer,
cellClassName: this._createRowClassNameGetter(),
cellStyle: this._createRowStyleGetter(),
columnWidth: width,
columnCount: 1,
estimatedRowSize: estimatedRowSize,
height: height,
noContentRenderer: noRowsRenderer,
onScroll: this._onScroll,
onSectionRendered: this._onSectionRendered,
overscanRowCount: overscanRowCount,
ref: "Grid",
rowHeight: rowHeight,
rowCount: rowCount,
scrollToAlignment: scrollToAlignment,
scrollToRow: scrollToIndex,
scrollTop: scrollTop,
style: style,
tabIndex: tabIndex,
width: width
});
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_cellRenderer",
value: function(_ref) {
var isScrolling = (_ref.columnIndex, _ref.isScrolling), rowIndex = _ref.rowIndex, rowRenderer = this.props.rowRenderer;
return rowRenderer({
index: rowIndex,
isScrolling: isScrolling
});
}
}, {
key: "_createRowClassNameGetter",
value: function() {
var rowClassName = this.props.rowClassName;
return rowClassName instanceof Function ? function(_ref2) {
var rowIndex = _ref2.rowIndex;
return rowClassName({
index: rowIndex
});
} : function() {
return rowClassName;
};
}
}, {
key: "_createRowStyleGetter",
value: function() {
var rowStyle = this.props.rowStyle, wrapped = rowStyle instanceof Function ? rowStyle : function() {
return rowStyle;
};
return function(_ref3) {
var rowIndex = _ref3.rowIndex;
return _extends({
width: "100%"
}, wrapped({
index: rowIndex
}));
};
}
}, {
key: "_onScroll",
value: function(_ref4) {
var clientHeight = _ref4.clientHeight, scrollHeight = _ref4.scrollHeight, scrollTop = _ref4.scrollTop, onScroll = this.props.onScroll;
onScroll({
clientHeight: clientHeight,
scrollHeight: scrollHeight,
scrollTop: scrollTop
});
}
}, {
key: "_onSectionRendered",
value: function(_ref5) {
var rowOverscanStartIndex = _ref5.rowOverscanStartIndex, rowOverscanStopIndex = _ref5.rowOverscanStopIndex, rowStartIndex = _ref5.rowStartIndex, rowStopIndex = _ref5.rowStopIndex, onRowsRendered = this.props.onRowsRendered;
onRowsRendered({
overscanStartIndex: rowOverscanStartIndex,
overscanStopIndex: rowOverscanStopIndex,
startIndex: rowStartIndex,
stopIndex: rowStopIndex
});
}
} ]), VirtualScroll;
}(_react.Component);
VirtualScroll.propTypes = {
"aria-label": _react.PropTypes.string,
autoHeight: _react.PropTypes.bool,
className: _react.PropTypes.string,
estimatedRowSize: _react.PropTypes.number.isRequired,
height: _react.PropTypes.number.isRequired,
noRowsRenderer: _react.PropTypes.func.isRequired,
onRowsRendered: _react.PropTypes.func.isRequired,
overscanRowCount: _react.PropTypes.number.isRequired,
onScroll: _react.PropTypes.func.isRequired,
rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired,
rowRenderer: _react.PropTypes.func.isRequired,
rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]),
rowCount: _react.PropTypes.number.isRequired,
rowStyle: _react.PropTypes.oneOfType([ _react.PropTypes.object, _react.PropTypes.func ]),
scrollToAlignment: _react.PropTypes.oneOf([ "auto", "end", "start", "center" ]).isRequired,
scrollToIndex: _react.PropTypes.number,
scrollTop: _react.PropTypes.number,
style: _react.PropTypes.object,
tabIndex: _react.PropTypes.number,
width: _react.PropTypes.number.isRequired
}, VirtualScroll.defaultProps = {
estimatedRowSize: 30,
noRowsRenderer: function() {
return null;
},
onRowsRendered: function() {
return null;
},
onScroll: function() {
return null;
},
overscanRowCount: 10,
scrollToAlignment: "auto",
style: {}
}, exports["default"] = VirtualScroll;
}, /* 206 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.WindowScroller = exports["default"] = void 0;
var _WindowScroller2 = __webpack_require__(207), _WindowScroller3 = _interopRequireDefault(_WindowScroller2);
exports["default"] = _WindowScroller3["default"], exports.WindowScroller = _WindowScroller3["default"];
}, /* 207 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _possibleConstructorReturn(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" != typeof call && "function" != typeof call ? self : call;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(10), _reactDom2 = _interopRequireDefault(_reactDom), _reactAddonsShallowCompare = __webpack_require__(4), _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare), _raf = __webpack_require__(176), _raf2 = _interopRequireDefault(_raf), IS_SCROLLING_TIMEOUT = 150, WindowScroller = function(_Component) {
function WindowScroller(props) {
_classCallCheck(this, WindowScroller);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(WindowScroller).call(this, props));
return _this.state = {
scrollTop: 0,
height: 0
}, _this._onScrollWindow = _this._onScrollWindow.bind(_this), _this._onResizeWindow = _this._onResizeWindow.bind(_this),
_this._enablePointerEventsAfterDelayCallback = _this._enablePointerEventsAfterDelayCallback.bind(_this),
_this;
}
return _inherits(WindowScroller, _Component), _createClass(WindowScroller, [ {
key: "componentDidMount",
value: function() {
this._positionFromTop = _reactDom2["default"].findDOMNode(this).getBoundingClientRect().top,
this.setState({
height: window.innerHeight
}), window.addEventListener("scroll", this._onScrollWindow, !1), window.addEventListener("resize", this._onResizeWindow, !1);
}
}, {
key: "componentWillUnmount",
value: function() {
window.removeEventListener("scroll", this._onScrollWindow, !1), window.removeEventListener("resize", this._onResizeWindow, !1);
}
}, {
key: "_setNextState",
value: function(state) {
var _this2 = this;
this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId),
this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() {
_this2._setNextStateAnimationFrameId = null, _this2.setState(state);
});
}
}, {
key: "render",
value: function() {
var children = this.props.children, _state = this.state, scrollTop = _state.scrollTop, height = _state.height;
return _react2["default"].createElement("div", null, children({
height: height,
scrollTop: scrollTop
}));
}
}, {
key: "shouldComponentUpdate",
value: function(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2["default"])(this, nextProps, nextState);
}
}, {
key: "_enablePointerEventsAfterDelay",
value: function() {
this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId),
this._disablePointerEventsTimeoutId = setTimeout(this._enablePointerEventsAfterDelayCallback, IS_SCROLLING_TIMEOUT);
}
}, {
key: "_enablePointerEventsAfterDelayCallback",
value: function() {
this._disablePointerEventsTimeoutId = null, document.body.style.pointerEvents = this._originalBodyPointerEvents,
this._originalBodyPointerEvents = null;
}
}, {
key: "_onResizeWindow",
value: function(event) {
var onResize = this.props.onResize, height = window.innerHeight || 0;
this.setState({
height: height
}), onResize({
height: height
});
}
}, {
key: "_onScrollWindow",
value: function(event) {
var onScroll = this.props.onScroll, scrollY = "scrollY" in window ? window.scrollY : document.documentElement.scrollTop, scrollTop = Math.max(0, scrollY - this._positionFromTop);
this._setNextState({
scrollTop: scrollTop
}), null == this._originalBodyPointerEvents && (this._originalBodyPointerEvents = document.body.style.pointerEvents,
document.body.style.pointerEvents = "none", this._enablePointerEventsAfterDelay()),
onScroll({
scrollTop: scrollTop
});
}
} ]), WindowScroller;
}(_react.Component);
WindowScroller.propTypes = {
children: _react.PropTypes.func.isRequired,
onResize: _react.PropTypes.func.isRequired,
onScroll: _react.PropTypes.func.isRequired
}, WindowScroller.defaultProps = {
onResize: function() {},
onScroll: function() {}
}, exports["default"] = WindowScroller;
} ]);
});
//# sourceMappingURL=react-virtualized.js.map |
src/components/Datepicker/Datepicker.Context.js | helpscout/blue | /* istanbul ignore file */
import React from 'react'
export const datepickerContextDefaultValue = {
enableRangeSelection: false,
endDate: null,
focusedDate: null,
startDate: null,
isDateFocused: () => false,
isDateSelected: () => false,
isDateHovered: () => false,
isDateBlocked: () => false,
isFirstOrLastSelectedDate: () => false,
onDateFocus: () => {},
onDateHover: () => {},
onDateSelect: () => {},
}
export default React.createContext(datepickerContextDefaultValue)
|
ajax/libs/hyperform/0.9.2/hyperform.amd.js | seogi1004/cdnjs | /*! hyperform.js.org */
define(function () { 'use strict';
var registry = Object.create(null);
/**
* run all actions registered for a hook
*
* Every action gets called with a state object as `this` argument and with the
* hook's call arguments as call arguments.
*
* @return mixed the returned value of the action calls or undefined
*/
function call_hook(hook) {
var result;
var call_args = Array.prototype.slice.call(arguments, 1);
if (hook in registry) {
result = registry[hook].reduce(function (args) {
return function (previousResult, currentAction) {
var interimResult = currentAction.apply({
state: previousResult,
hook: hook
}, args);
return interimResult !== undefined ? interimResult : previousResult;
};
}(call_args), result);
}
return result;
}
/**
* Filter a value through hooked functions
*
* Allows for additional parameters:
* js> do_filter('foo', null, current_element)
*/
function do_filter(hook, initial_value) {
var result = initial_value;
var call_args = Array.prototype.slice.call(arguments, 1);
if (hook in registry) {
result = registry[hook].reduce(function (previousResult, currentAction) {
call_args[0] = previousResult;
var interimResult = currentAction.apply({
state: previousResult,
hook: hook
}, call_args);
return interimResult !== undefined ? interimResult : previousResult;
}, result);
}
return result;
}
/**
* remove an action again
*/
function remove_hook(hook, action) {
if (hook in registry) {
for (var i = 0; i < registry[hook].length; i++) {
if (registry[hook][i] === action) {
registry[hook].splice(i, 1);
break;
}
}
}
}
/**
* add an action to a hook
*/
function add_hook(hook, action, position) {
if (!(hook in registry)) {
registry[hook] = [];
}
if (position === undefined) {
position = registry[hook].length;
}
registry[hook].splice(position, 0, action);
}
/**
* return either the data of a hook call or the result of action, if the
* former is undefined
*
* @return function a function wrapper around action
*/
function return_hook_or (hook, action) {
return function () {
var data = call_hook(hook, Array.prototype.slice.call(arguments));
if (data !== undefined) {
return data;
}
return action.apply(this, arguments);
};
}
/* the following code is borrowed from the WebComponents project, licensed
* under the BSD license. Source:
* <https://github.com/webcomponents/webcomponentsjs/blob/5283db1459fa2323e5bfc8b9b5cc1753ed85e3d0/src/WebComponents/dom.js#L53-L78>
*/
// defaultPrevented is broken in IE.
// https://connect.microsoft.com/IE/feedback/details/790389/event-defaultprevented-returns-false-after-preventdefault-was-called
var workingDefaultPrevented = function () {
var e = document.createEvent('Event');
e.initEvent('foo', true, true);
e.preventDefault();
return e.defaultPrevented;
}();
if (!workingDefaultPrevented) {
(function () {
var origPreventDefault = window.Event.prototype.preventDefault;
window.Event.prototype.preventDefault = function () {
if (!this.cancelable) {
return;
}
origPreventDefault.call(this);
Object.defineProperty(this, 'defaultPrevented', {
get: function get() {
return true;
},
configurable: true
});
};
})();
}
/* end of borrowed code */
function create_event(name) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _ref$bubbles = _ref.bubbles;
var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles;
var _ref$cancelable = _ref.cancelable;
var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable;
var event = document.createEvent('Event');
event.initEvent(name, bubbles, cancelable);
return event;
}
function trigger_event (element, event) {
var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var _ref2$bubbles = _ref2.bubbles;
var bubbles = _ref2$bubbles === undefined ? true : _ref2$bubbles;
var _ref2$cancelable = _ref2.cancelable;
var cancelable = _ref2$cancelable === undefined ? false : _ref2$cancelable;
var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (!(event instanceof window.Event)) {
event = create_event(event, { bubbles: bubbles, cancelable: cancelable });
}
for (var key in payload) {
if (payload.hasOwnProperty(key)) {
event[key] = payload[key];
}
}
element.dispatchEvent(event);
return event;
}
/* and datetime-local? Spec says “Nah!” */
var dates = ['datetime', 'date', 'month', 'week', 'time'];
var plain_numbers = ['number', 'range'];
/* everything that returns something meaningful for valueAsNumber and
* can have the step attribute */
var numbers = dates.concat(plain_numbers, 'datetime-local');
/* the spec says to only check those for syntax in validity.typeMismatch.
* ¯\_(ツ)_/¯ */
var type_checked = ['email', 'url'];
/* check these for validity.badInput */
var input_checked = ['email', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'number', 'range', 'color'];
var text_types = ['text', 'search', 'tel', 'password'].concat(type_checked);
/* input element types, that are candidates for the validation API.
* Missing from this set are: button, hidden, menu (from <button>), reset and
* the types for non-<input> elements. */
var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text_types);
/* all known types of <input> */
var inputs = ['button', 'hidden', 'reset'].concat(validation_candidates);
/* apparently <select> and <textarea> have types of their own */
var non_inputs = ['select-one', 'select-multiple', 'textarea'];
/* shim layer for the Element.matches method */
var ep = window.Element.prototype;
var native_matches = ep.matches || ep.matchesSelector || ep.msMatchesSelector || ep.webkitMatchesSelector;
function matches (element, selector) {
return native_matches.call(element, selector);
}
/**
* mark an object with a '__hyperform=true' property
*
* We use this to distinguish our properties from the native ones. Usage:
* js> mark(obj);
* js> assert(obj.__hyperform === true)
*/
function mark (obj) {
if (['object', 'function'].indexOf(typeof obj) > -1) {
delete obj.__hyperform;
Object.defineProperty(obj, '__hyperform', {
configurable: true,
enumerable: false,
value: true
});
}
return obj;
}
/**
* the internal storage for messages
*/
var store = new WeakMap();
/* jshint -W053 */
var message_store = {
set: function set(element, message) {
var is_custom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (element instanceof window.HTMLFieldSetElement) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && !wrapped_form.settings.extendFieldset) {
/* make this a no-op for <fieldset> in strict mode */
return message_store;
}
}
if (typeof message === 'string') {
message = new String(message);
}
if (is_custom) {
message.is_custom = true;
}
mark(message);
store.set(element, message);
/* allow the :invalid selector to match */
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity(message.toString());
}
return message_store;
},
get: function get(element) {
var message = store.get(element);
if (message === undefined && '_original_validationMessage' in element) {
/* get the browser's validation message, if we have none. Maybe it
* knows more than we. */
message = new String(element._original_validationMessage);
}
return message ? message : new String('');
},
delete: function _delete(element) {
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity('');
}
return store.delete(element);
}
};
/**
* counter that will be incremented with every call
*
* Will enforce uniqueness, as long as no more than 1 hyperform scripts
* are loaded. (In that case we still have the "random" part below.)
*/
var uid = 0;
/**
* generate a random ID
*
* @see https://gist.github.com/gordonbrander/2230317
*/
function generate_id () {
var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'hf_';
return prefix + uid++ + Math.random().toString(36).substr(2);
}
var warningsCache = new WeakMap();
var DefaultRenderer = {
/**
* called when a warning should become visible
*/
attachWarning: function attachWarning(warning, element) {
/* should also work, if element is last,
* http://stackoverflow.com/a/4793630/113195 */
element.parentNode.insertBefore(warning, element.nextSibling);
},
/**
* called when a warning should vanish
*/
detachWarning: function detachWarning(warning, element) {
warning.parentNode.removeChild(warning);
},
/**
* called when feedback to an element's state should be handled
*
* i.e., showing and hiding warnings
*/
showWarning: function showWarning(element) {
var sub_radio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var msg = message_store.get(element).toString();
var warning = warningsCache.get(element);
if (msg) {
if (!warning) {
var wrapper = get_wrapper(element);
warning = document.createElement('div');
warning.className = wrapper && wrapper.settings.classes.warning || 'hf-warning';
warning.id = generate_id();
warning.setAttribute('aria-live', 'polite');
warningsCache.set(element, warning);
}
element.setAttribute('aria-errormessage', warning.id);
warning.textContent = msg;
Renderer.attachWarning(warning, element);
} else if (warning && warning.parentNode) {
element.removeAttribute('aria-errormessage');
Renderer.detachWarning(warning, element);
}
if (!sub_radio && element.type === 'radio' && element.form) {
/* render warnings for all other same-name radios, too */
Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form;
}).map(function (radio) {
return Renderer.showWarning(radio, 'sub_radio');
});
}
}
};
var Renderer = {
attachWarning: DefaultRenderer.attachWarning,
detachWarning: DefaultRenderer.detachWarning,
showWarning: DefaultRenderer.showWarning,
set: function set(renderer, action) {
if (renderer.indexOf('_') > -1) {
/* global console */
// TODO delete before next non-patch version
console.log('Renderer.set: please use camelCase names. ' + renderer + ' will be removed in the next non-patch release.');
renderer = renderer.replace(/_([a-z])/g, function (g) {
return g[1].toUpperCase();
});
}
if (!action) {
action = DefaultRenderer[renderer];
}
Renderer[renderer] = action;
}
};
/**
* check element's validity and report an error back to the user
*/
function reportValidity(element) {
/* if this is a <form>, report validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, reportValidity).every(function (b) {
return b;
});
}
/* we copy checkValidity() here, b/c we have to check if the "invalid"
* event was canceled. */
var valid = ValidityState(element).valid;
var event;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.validEvent) {
event = trigger_event(element, 'valid', { cancelable: true });
}
} else {
event = trigger_event(element, 'invalid', { cancelable: true });
}
if (!event || !event.defaultPrevented) {
Renderer.showWarning(element);
}
return valid;
}
/**
* submit a form, because `element` triggered it
*
* This method also dispatches a submit event on the form prior to the
* submission. The event contains the trigger element as `submittedVia`.
*
* If the element is a button with a name, the name=value pair will be added
* to the submitted data.
*/
function submit_form_via(element) {
/* apparently, the submit event is not triggered in most browsers on
* the submit() method, so we do it manually here to model a natural
* submit as closely as possible.
* Now to the fun fact: If you trigger a submit event from a form, what
* do you think should happen?
* 1) the form will be automagically submitted by the browser, or
* 2) nothing.
* And as you already suspected, the correct answer is: both! Firefox
* opts for 1), Chrome for 2). Yay! */
var event_got_cancelled;
var submit_event = create_event('submit', { cancelable: true });
/* force Firefox to not submit the form, then fake preventDefault() */
submit_event.preventDefault();
Object.defineProperty(submit_event, 'defaultPrevented', {
value: false,
writable: true
});
Object.defineProperty(submit_event, 'preventDefault', {
value: function value() {
return submit_event.defaultPrevented = event_got_cancelled = true;
},
writable: true
});
trigger_event(element.form, submit_event, {}, { submittedVia: element });
if (!event_got_cancelled) {
add_submit_field(element);
window.HTMLFormElement.prototype.submit.call(element.form);
window.setTimeout(function () {
return remove_submit_field(element);
});
}
}
/**
* if a submit button was clicked, add its name=value by means of a type=hidden
* input field
*/
function add_submit_field(button) {
if (['image', 'submit'].indexOf(button.type) > -1 && button.name) {
var wrapper = get_wrapper(button.form) || {};
var submit_helper = wrapper.submit_helper;
if (submit_helper) {
if (submit_helper.parentNode) {
submit_helper.parentNode.removeChild(submit_helper);
}
} else {
submit_helper = document.createElement('input');
submit_helper.type = 'hidden';
wrapper.submit_helper = submit_helper;
}
submit_helper.name = button.name;
submit_helper.value = button.value;
button.form.appendChild(submit_helper);
}
}
/**
* remove a possible helper input, that was added by `add_submit_field`
*/
function remove_submit_field(button) {
if (['image', 'submit'].indexOf(button.type) > -1 && button.name) {
var wrapper = get_wrapper(button.form) || {};
var submit_helper = wrapper.submit_helper;
if (submit_helper && submit_helper.parentNode) {
submit_helper.parentNode.removeChild(submit_helper);
}
}
}
/**
* check a form's validity and submit it
*
* The method triggers a cancellable `validate` event on the form. If the
* event is cancelled, form submission will be aborted, too.
*
* If the form is found to contain invalid fields, focus the first field.
*/
function check(button) {
/* trigger a "validate" event on the form to be submitted */
var val_event = trigger_event(button.form, 'validate', { cancelable: true });
if (val_event.defaultPrevented) {
/* skip the whole submit thing, if the validation is canceled. A user
* can still call form.submit() afterwards. */
return;
}
var valid = true;
var first_invalid;
Array.prototype.map.call(button.form.elements, function (element) {
if (!reportValidity(element)) {
valid = false;
if (!first_invalid && 'focus' in element) {
first_invalid = element;
}
}
});
if (valid) {
submit_form_via(button);
} else if (first_invalid) {
/* focus the first invalid element, if validation went south */
first_invalid.focus();
}
}
/**
* test if node is a submit button
*/
function is_submit_button(node) {
return (
/* must be an input or button element... */
(node.nodeName === 'INPUT' || node.nodeName === 'BUTTON') && (
/* ...and have a submitting type */
node.type === 'image' || node.type === 'submit')
);
}
/**
* test, if the click event would trigger a submit
*/
function is_submitting_click(event, button) {
return (
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* left button or middle button (submits in Chrome) */
!('button' in event) || event.button < 2) &&
/* must be a submit button... */
is_submit_button(button) &&
/* the button needs a form, that's going to be submitted */
button.form &&
/* again, if the form should not be validated, we're out of the game */
!button.form.hasAttribute('novalidate')
);
}
/**
* test, if the keypress event would trigger a submit
*/
function is_submitting_keypress(event) {
return (
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* ...and <Enter> was pressed... */
event.keyCode === 13 &&
/* ...on an <input> that is... */
event.target.nodeName === 'INPUT' &&
/* ...a standard text input field (not checkbox, ...) */
text_types.indexOf(event.target.type) > -1 ||
/* or <Enter> or <Space> was pressed... */
(event.keyCode === 13 || event.keyCode === 32) &&
/* ...on a submit button */
is_submit_button(event.target)) &&
/* there's a form... */
event.target.form &&
/* ...and the form allows validation */
!event.target.form.hasAttribute('novalidate')
);
}
/**
* catch clicks to children of <button>s
*/
function get_clicked_button(element) {
if (is_submit_button(element)) {
return element;
} else if (matches(element, 'button:not([type]) *, button[type="submit"] *')) {
return get_clicked_button(element.parentNode);
} else {
return null;
}
}
/**
* return event handler to catch explicit submission by click on a button
*/
function get_click_handler() {
var ignore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
return function (event) {
var button = get_clicked_button(event.target);
if (button && is_submitting_click(event, button)) {
event.preventDefault();
if (ignore || button.hasAttribute('formnovalidate')) {
/* if validation should be ignored, we're not interested in any checks */
submit_form_via(button);
} else {
check(button);
}
}
};
}
var click_handler = get_click_handler();
var ignored_click_handler = get_click_handler(true);
/**
* catch implicit submission by pressing <Enter> in some situations
*/
function get_keypress_handler(ignore) {
return function keypress_handler(event) {
if (is_submitting_keypress(event)) {
event.preventDefault();
var wrapper = get_wrapper(event.target.form) || { settings: {} };
if (wrapper.settings.preventImplicitSubmit) {
/* user doesn't want an implicit submit. Cancel here. */
return;
}
/* check, that there is no submit button in the form. Otherwise
* that should be clicked. */
var el = event.target.form.elements.length;
var submit;
for (var i = 0; i < el; i++) {
if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) {
submit = event.target.form.elements[i];
break;
}
}
if (submit) {
submit.click();
} else if (ignore) {
submit_form_via(event.target);
} else {
check(event.target);
}
}
};
}
var keypress_handler = get_keypress_handler();
var ignored_keypress_handler = get_keypress_handler(true);
/**
* catch all relevant events _prior_ to a form being submitted
*
* @param bool ignore bypass validation, when an attempt to submit the
* form is detected. True, when the wrapper's revalidate
* setting is 'never'.
*/
function catch_submit(listening_node) {
var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (ignore) {
listening_node.addEventListener('click', ignored_click_handler);
listening_node.addEventListener('keypress', ignored_keypress_handler);
} else {
listening_node.addEventListener('click', click_handler);
listening_node.addEventListener('keypress', keypress_handler);
}
}
/**
* decommission the event listeners from catch_submit() again
*/
function uncatch_submit(listening_node) {
listening_node.removeEventListener('click', ignored_click_handler);
listening_node.removeEventListener('keypress', ignored_keypress_handler);
listening_node.removeEventListener('click', click_handler);
listening_node.removeEventListener('keypress', keypress_handler);
}
/**
* remove `property` from element and restore _original_property, if present
*/
function uninstall_property (element, property) {
try {
delete element[property];
} catch (e) {
/* Safari <= 9 and PhantomJS will end up here :-( Nothing to do except
* warning */
var wrapper = get_wrapper(element);
if (wrapper && wrapper.settings.debug) {
/* global console */
console.log('[hyperform] cannot uninstall custom property ' + property);
}
return false;
}
var original_descriptor = Object.getOwnPropertyDescriptor(element, '_original_' + property);
if (original_descriptor) {
Object.defineProperty(element, property, original_descriptor);
}
}
/**
* add `property` to an element
*
* js> installer(element, 'foo', { value: 'bar' });
* js> assert(element.foo === 'bar');
*/
function install_property (element, property, descriptor) {
descriptor.configurable = true;
descriptor.enumerable = true;
if ('value' in descriptor) {
descriptor.writable = true;
}
var original_descriptor = Object.getOwnPropertyDescriptor(element, property);
if (original_descriptor) {
if (original_descriptor.configurable === false) {
/* Safari <= 9 and PhantomJS will end up here :-( Nothing to do except
* warning */
var wrapper = get_wrapper(element);
if (wrapper && wrapper.settings.debug) {
/* global console */
console.log('[hyperform] cannot install custom property ' + property);
}
return false;
}
/* we already installed that property... */
if (original_descriptor.get && original_descriptor.get.__hyperform || original_descriptor.value && original_descriptor.value.__hyperform) {
return;
}
/* publish existing property under new name, if it's not from us */
Object.defineProperty(element, '_original_' + property, original_descriptor);
}
delete element[property];
Object.defineProperty(element, property, descriptor);
return true;
}
function is_field (element) {
return element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement || element === window.HTMLButtonElement.prototype || element === window.HTMLInputElement.prototype || element === window.HTMLSelectElement.prototype || element === window.HTMLTextAreaElement.prototype || element === window.HTMLFieldSetElement.prototype;
}
/**
* set a custom validity message or delete it with an empty string
*/
function setCustomValidity(element, msg) {
message_store.set(element, msg, true);
}
function sprintf (str) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var args_length = args.length;
var global_index = 0;
return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) {
var local_index = global_index;
if (position) {
local_index = Number(position.replace(/\$$/, '')) - 1;
}
global_index += 1;
var arg = '';
if (args_length > local_index) {
arg = args[local_index];
}
if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) {
/* try getting a localized representation of dates and numbers, if the
* browser supports this */
if (type === 'l') {
arg = (arg.toLocaleString || arg.toString).call(arg);
} else {
arg = arg.toString();
}
}
return arg;
});
}
/* For a given date, get the ISO week number
*
* Source: http://stackoverflow.com/a/6117889/113195
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function get_week_of_year (d) {
/* Copy date so don't modify original */
d = new Date(+d);
d.setUTCHours(0, 0, 0);
/* Set to nearest Thursday: current date + 4 - current day number
* Make Sunday's day number 7 */
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
/* Get first day of year */
var yearStart = new Date(d.getUTCFullYear(), 0, 1);
/* Calculate full weeks to nearest Thursday */
var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
/* Return array of year and week number */
return [d.getUTCFullYear(), weekNo];
}
function pad(num) {
var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
/**
* calculate a string from a date according to HTML5
*/
function date_to_string(date, element_type) {
if (!(date instanceof Date)) {
return null;
}
switch (element_type) {
case 'datetime':
return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time');
case 'datetime-local':
return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
case 'date':
return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate()));
case 'month':
return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1));
case 'week':
var params = get_week_of_year(date);
return sprintf.call(null, '%s-W%s', params[0], pad(params[1]));
case 'time':
return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
}
return null;
}
/**
* return a new Date() representing the ISO date for a week number
*
* @see http://stackoverflow.com/a/16591175/113195
*/
function get_date_from_week (week, year) {
var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7));
if (date.getUTCDay() <= 4 /* thursday */) {
date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1);
} else {
date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay());
}
return date;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_date (string, element_type) {
var date = new Date(0);
var ms;
switch (element_type) {
case 'datetime':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$7 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
date.setUTCHours(Number(RegExp.$4), Number(RegExp.$5), Number(RegExp.$6 || 0), Number(ms));
return date;
case 'date':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
return date;
case 'month':
if (!/^([0-9]{4,})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, 1);
return date;
case 'week':
if (!/^([0-9]{4,})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) {
return null;
}
return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1));
case 'time':
if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$4 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCHours(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3 || 0), Number(ms));
return date;
}
return null;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_number (string, element_type) {
var rval = string_to_date(string, element_type);
if (rval !== null) {
return +rval;
}
/* not parseFloat, because we want NaN for invalid values like "1.2xxy" */
return Number(string);
}
/**
* get the element's type in a backwards-compatible way
*/
function get_type (element) {
if (element instanceof window.HTMLTextAreaElement) {
return 'textarea';
} else if (element instanceof window.HTMLSelectElement) {
return element.hasAttribute('multiple') ? 'select-multiple' : 'select-one';
} else if (element instanceof window.HTMLButtonElement) {
return (element.getAttribute('type') || 'submit').toLowerCase();
} else if (element instanceof window.HTMLInputElement) {
var attr = (element.getAttribute('type') || '').toLowerCase();
if (attr && inputs.indexOf(attr) > -1) {
return attr;
} else {
/* perhaps the DOM has in-depth knowledge. Take that before returning
* 'text'. */
return element.type || 'text';
}
}
return '';
}
/**
* the following validation messages are from Firefox source,
* http://mxr.mozilla.org/mozilla-central/source/dom/locales/en-US/chrome/dom/dom.properties
* released under MPL license, http://mozilla.org/MPL/2.0/.
*/
var catalog = {
en: {
TextTooLong: 'Please shorten this text to %l characters or less (you are currently using %l characters).',
ValueMissing: 'Please fill out this field.',
CheckboxMissing: 'Please check this box if you want to proceed.',
RadioMissing: 'Please select one of these options.',
FileMissing: 'Please select a file.',
SelectMissing: 'Please select an item in the list.',
InvalidEmail: 'Please enter an email address.',
InvalidURL: 'Please enter a URL.',
PatternMismatch: 'Please match the requested format.',
PatternMismatchWithTitle: 'Please match the requested format: %l.',
NumberRangeOverflow: 'Please select a value that is no more than %l.',
DateRangeOverflow: 'Please select a value that is no later than %l.',
TimeRangeOverflow: 'Please select a value that is no later than %l.',
NumberRangeUnderflow: 'Please select a value that is no less than %l.',
DateRangeUnderflow: 'Please select a value that is no earlier than %l.',
TimeRangeUnderflow: 'Please select a value that is no earlier than %l.',
StepMismatch: 'Please select a valid value. The two nearest valid values are %l and %l.',
StepMismatchOneValue: 'Please select a valid value. The nearest valid value is %l.',
BadInputNumber: 'Please enter a number.'
}
};
/**
* the global language Hyperform will use
*/
var language = 'en';
/**
* set the language for Hyperform’s messages
*/
function set_language(newlang) {
language = newlang;
}
/**
* add a lookup catalog "string: translation" for a language
*/
function add_translation(lang, new_catalog) {
if (!(lang in catalog)) {
catalog[lang] = {};
}
for (var key in new_catalog) {
if (new_catalog.hasOwnProperty(key)) {
catalog[lang][key] = new_catalog[key];
}
}
}
/**
* return `s` translated into the current language
*
* Defaults to English if the former has no translation for `s`.
*/
function _ (s) {
if (language in catalog && s in catalog[language]) {
return catalog[language][s];
} else if (s in catalog.en) {
return catalog.en[s];
}
return s;
}
var default_step = {
'datetime-local': 60,
datetime: 60,
time: 60
};
var step_scale_factor = {
'datetime-local': 1000,
datetime: 1000,
date: 86400000,
week: 604800000,
time: 1000
};
var default_step_base = {
week: -259200000
};
var default_min = {
range: 0
};
var default_max = {
range: 100
};
/**
* get previous and next valid values for a stepped input element
*/
function get_next_valid (element) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var type = get_type(element);
var aMin = element.getAttribute('min');
var min = default_min[type] || NaN;
if (aMin) {
var pMin = string_to_number(aMin, type);
if (!isNaN(pMin)) {
min = pMin;
}
}
var aMax = element.getAttribute('max');
var max = default_max[type] || NaN;
if (aMax) {
var pMax = string_to_number(aMax, type);
if (!isNaN(pMax)) {
max = pMax;
}
}
var aStep = element.getAttribute('step');
var step = default_step[type] || 1;
if (aStep && aStep.toLowerCase() === 'any') {
/* quick return: we cannot calculate prev and next */
return [_('any value'), _('any value')];
} else if (aStep) {
var pStep = string_to_number(aStep, type);
if (!isNaN(pStep)) {
step = pStep;
}
}
var default_value = string_to_number(element.getAttribute('value'), type);
var value = string_to_number(element.value || element.getAttribute('value'), type);
if (isNaN(value)) {
/* quick return: we cannot calculate without a solid base */
return [_('any valid value'), _('any valid value')];
}
var step_base = !isNaN(min) ? min : !isNaN(default_value) ? default_value : default_step_base[type] || 0;
var scale = step_scale_factor[type] || 1;
var prev = step_base + Math.floor((value - step_base) / (step * scale)) * (step * scale) * n;
var next = step_base + (Math.floor((value - step_base) / (step * scale)) + 1) * (step * scale) * n;
if (prev < min) {
prev = null;
} else if (prev > max) {
prev = max;
}
if (next > max) {
next = null;
} else if (next < min) {
next = min;
}
/* convert to date objects, if appropriate */
if (dates.indexOf(type) > -1) {
prev = date_to_string(new Date(prev), type);
next = date_to_string(new Date(next), type);
}
return [prev, next];
}
/**
* implement the valueAsDate functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate
*/
function valueAsDate(element) {
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var type = get_type(element);
if (dates.indexOf(type) > -1) {
if (value !== undefined) {
/* setter: value must be null or a Date() */
if (value === null) {
element.value = '';
} else if (value instanceof Date) {
if (isNaN(value.getTime())) {
element.value = '';
} else {
element.value = date_to_string(value, type);
}
} else {
throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError');
}
return;
}
var value_date = string_to_date(element.value, type);
return value_date instanceof Date ? value_date : null;
} else if (value !== undefined) {
/* trying to set a date on a not-date input fails */
throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError');
}
return null;
}
/**
* implement the valueAsNumber functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber
*/
function valueAsNumber(element) {
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var type = get_type(element);
if (numbers.indexOf(type) > -1) {
if (type === 'range' && element.hasAttribute('multiple')) {
/* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */
return NaN;
}
if (value !== undefined) {
/* setter: value must be NaN or a finite number */
if (isNaN(value)) {
element.value = '';
} else if (typeof value === 'number' && window.isFinite(value)) {
try {
/* try setting as a date, but... */
valueAsDate(element, new Date(value));
} catch (e) {
/* ... when valueAsDate is not responsible, ... */
if (!(e instanceof window.DOMException)) {
throw e;
}
/* ... set it via Number.toString(). */
element.value = value.toString();
}
} else {
throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError');
}
return;
}
return string_to_number(element.value, type);
} else if (value !== undefined) {
/* trying to set a number on a not-number input fails */
throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError');
}
return NaN;
}
/**
*
*/
function stepDown(element) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepDown encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepDown encountered step "any"', 'InvalidStateError');
}
var prev = get_next_valid(element, n)[0];
if (prev !== null) {
valueAsNumber(element, prev);
}
}
/**
*
*/
function stepUp(element) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepUp encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepUp encountered step "any"', 'InvalidStateError');
}
var next = get_next_valid(element, n)[1];
if (next !== null) {
valueAsNumber(element, next);
}
}
/**
* get the validation message for an element, empty string, if the element
* satisfies all constraints.
*/
function validationMessage(element) {
var msg = message_store.get(element);
if (!msg) {
return '';
}
/* make it a primitive again, since message_store returns String(). */
return msg.toString();
}
/**
* check, if an element will be subject to HTML5 validation at all
*/
function willValidate(element) {
return is_validation_candidate(element);
}
var gA = function gA(prop) {
return function () {
return do_filter('attr_get_' + prop, this.getAttribute(prop), this);
};
};
var sA = function sA(prop) {
return function (value) {
this.setAttribute(prop, do_filter('attr_set_' + prop, value, this));
};
};
var gAb = function gAb(prop) {
return function () {
return do_filter('attr_get_' + prop, this.hasAttribute(prop), this);
};
};
var sAb = function sAb(prop) {
return function (value) {
if (do_filter('attr_set_' + prop, value, this)) {
this.setAttribute(prop, prop);
} else {
this.removeAttribute(prop);
}
};
};
var gAn = function gAn(prop) {
return function () {
return do_filter('attr_get_' + prop, Math.max(0, Number(this.getAttribute(prop))), this);
};
};
var sAn = function sAn(prop) {
return function (value) {
value = do_filter('attr_set_' + prop, value, this);
if (/^[0-9]+$/.test(value)) {
this.setAttribute(prop, value);
}
};
};
function install_properties(element) {
var _arr = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step'];
for (var _i = 0; _i < _arr.length; _i++) {
var prop = _arr[_i];
install_property(element, prop, {
get: gA(prop),
set: sA(prop)
});
}
var _arr2 = ['multiple', 'required', 'readOnly'];
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var _prop = _arr2[_i2];
install_property(element, _prop, {
get: gAb(_prop.toLowerCase()),
set: sAb(_prop.toLowerCase())
});
}
var _arr3 = ['minLength', 'maxLength'];
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var _prop2 = _arr3[_i3];
install_property(element, _prop2, {
get: gAn(_prop2.toLowerCase()),
set: sAn(_prop2.toLowerCase())
});
}
}
function uninstall_properties(element) {
var _arr4 = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step', 'multiple', 'required', 'readOnly', 'minLength', 'maxLength'];
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var prop = _arr4[_i4];
uninstall_property(element, prop);
}
}
var polyfills = {
checkValidity: {
value: mark(function () {
return checkValidity(this);
})
},
reportValidity: {
value: mark(function () {
return reportValidity(this);
})
},
setCustomValidity: {
value: mark(function (msg) {
return setCustomValidity(this, msg);
})
},
stepDown: {
value: mark(function () {
var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return stepDown(this, n);
})
},
stepUp: {
value: mark(function () {
var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return stepUp(this, n);
})
},
validationMessage: {
get: mark(function () {
return validationMessage(this);
})
},
validity: {
get: mark(function () {
return ValidityState(this);
})
},
valueAsDate: {
get: mark(function () {
return valueAsDate(this);
}),
set: mark(function (value) {
valueAsDate(this, value);
})
},
valueAsNumber: {
get: mark(function () {
return valueAsNumber(this);
}),
set: mark(function (value) {
valueAsNumber(this, value);
})
},
willValidate: {
get: mark(function () {
return willValidate(this);
})
}
};
function polyfill (element) {
if (is_field(element)) {
for (var prop in polyfills) {
install_property(element, prop, polyfills[prop]);
}
install_properties(element);
} else if (element instanceof window.HTMLFormElement || element === window.HTMLFormElement.prototype) {
install_property(element, 'checkValidity', polyfills.checkValidity);
install_property(element, 'reportValidity', polyfills.reportValidity);
}
}
function polyunfill (element) {
if (is_field(element)) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
uninstall_property(element, 'setCustomValidity');
uninstall_property(element, 'stepDown');
uninstall_property(element, 'stepUp');
uninstall_property(element, 'validationMessage');
uninstall_property(element, 'validity');
uninstall_property(element, 'valueAsDate');
uninstall_property(element, 'valueAsNumber');
uninstall_property(element, 'willValidate');
uninstall_properties(element);
} else if (element instanceof window.HTMLFormElement) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
}
}
var instances = new WeakMap();
/**
* wrap <form>s, window or document, that get treated with the global
* hyperform()
*/
function Wrapper(form, settings) {
/* do not allow more than one instance per form. Otherwise we'd end
* up with double event handlers, polyfills re-applied, ... */
var existing = instances.get(form);
if (existing) {
existing.settings = settings;
return existing;
}
this.form = form;
this.settings = settings;
this.revalidator = this.revalidate.bind(this);
instances.set(form, this);
catch_submit(form, settings.revalidate === 'never');
if (form === window || form.nodeType === 9) {
/* install on the prototypes, when called for the whole document */
this.install([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyfill(window.HTMLFormElement);
} else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) {
this.install(form.elements);
if (form instanceof window.HTMLFormElement) {
polyfill(form);
}
}
if (settings.revalidate === 'oninput' || settings.revalidate === 'hybrid') {
/* in a perfect world we'd just bind to "input", but support here is
* abysmal: http://caniuse.com/#feat=input-event */
form.addEventListener('keyup', this.revalidator);
form.addEventListener('change', this.revalidator);
}
if (settings.revalidate === 'onblur' || settings.revalidate === 'hybrid') {
/* useCapture=true, because `blur` doesn't bubble. See
* https://developer.mozilla.org/en-US/docs/Web/Events/blur#Event_delegation
* for a discussion */
form.addEventListener('blur', this.revalidator, true);
}
}
Wrapper.prototype = {
destroy: function destroy() {
uncatch_submit(this.form);
instances.delete(this.form);
this.form.removeEventListener('keyup', this.revalidator);
this.form.removeEventListener('change', this.revalidator);
this.form.removeEventListener('blur', this.revalidator, true);
if (this.form === window || this.form.nodeType === 9) {
this.uninstall([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyunfill(window.HTMLFormElement);
} else if (this.form instanceof window.HTMLFormElement || this.form instanceof window.HTMLFieldSetElement) {
this.uninstall(this.form.elements);
if (this.form instanceof window.HTMLFormElement) {
polyunfill(this.form);
}
}
},
/**
* revalidate an input element
*/
revalidate: function revalidate(event) {
if (event.target instanceof window.HTMLButtonElement || event.target instanceof window.HTMLTextAreaElement || event.target instanceof window.HTMLSelectElement || event.target instanceof window.HTMLInputElement) {
if (this.settings.revalidate === 'hybrid') {
/* "hybrid" somewhat simulates what browsers do. See for example
* Firefox's :-moz-ui-invalid pseudo-class:
* https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid */
if (event.type === 'blur' && event.target.value !== event.target.defaultValue || ValidityState(event.target).valid) {
/* on blur, update the report when the value has changed from the
* default or when the element is valid (possibly removing a still
* standing invalidity report). */
reportValidity(event.target);
} else if (event.type === 'keyup' || event.type === 'change') {
if (ValidityState(event.target).valid) {
// report instantly, when an element becomes valid,
// postpone report to blur event, when an element is invalid
reportValidity(event.target);
}
}
} else {
reportValidity(event.target);
}
}
},
/**
* install the polyfills on each given element
*
* If you add elements dynamically, you have to call install() on them
* yourself:
*
* js> var form = hyperform(document.forms[0]);
* js> document.forms[0].appendChild(input);
* js> form.install(input);
*
* You can skip this, if you called hyperform on window or document.
*/
install: function install(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyfill(els[i]);
}
},
uninstall: function uninstall(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyunfill(els[i]);
}
}
};
/**
* try to get the appropriate wrapper for a specific element by looking up
* its parent chain
*
* @return Wrapper | undefined
*/
function get_wrapper(element) {
var wrapped;
if (element.form) {
/* try a shortcut with the element's <form> */
wrapped = instances.get(element.form);
}
/* walk up the parent nodes until document (including) */
while (!wrapped && element) {
wrapped = instances.get(element);
element = element.parentNode;
}
if (!wrapped) {
/* try the global instance, if exists. This may also be undefined. */
wrapped = instances.get(window);
}
return wrapped;
}
/**
* check if an element is a candidate for constraint validation
*
* @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation
*/
function is_validation_candidate (element) {
/* allow a shortcut via filters, e.g. to validate type=hidden fields */
var filtered = do_filter('is_validation_candidate', null, element);
if (filtered !== null) {
return !!filtered;
}
/* it must be any of those elements */
if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) {
var type = get_type(element);
/* its type must be in the whitelist or missing (select, textarea) */
if (!type || non_inputs.indexOf(type) > -1 || validation_candidates.indexOf(type) > -1) {
/* it mustn't be disabled or readonly */
if (!element.hasAttribute('disabled') && !element.hasAttribute('readonly')) {
var wrapped_form = get_wrapper(element);
/* it hasn't got the (non-standard) attribute 'novalidate' or its
* parent form has got the strict parameter */
if (wrapped_form && wrapped_form.settings.novalidateOnElements || !element.hasAttribute('novalidate') || !element.noValidate) {
/* it isn't part of a <fieldset disabled> */
var p = element.parentNode;
while (p && p.nodeType === 1) {
if (p instanceof window.HTMLFieldSetElement && p.hasAttribute('disabled')) {
/* quick return, if it's a child of a disabled fieldset */
return false;
} else if (p.nodeName.toUpperCase() === 'DATALIST') {
/* quick return, if it's a child of a datalist
* Do not use HTMLDataListElement to support older browsers,
* too.
* @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element:barred-from-constraint-validation
*/
return false;
} else if (p === element.form) {
/* the outer boundary. We can stop looking for relevant
* fieldsets. */
break;
}
p = p.parentNode;
}
/* then it's a candidate */
return true;
}
}
}
}
/* this is no HTML5 validation candidate... */
return false;
}
function format_date (date) {
var part = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
switch (part) {
case 'date':
return (date.toLocaleDateString || date.toDateString).call(date);
case 'time':
return (date.toLocaleTimeString || date.toTimeString).call(date);
case 'month':
return 'toLocaleDateString' in date ? date.toLocaleDateString(undefined, {
year: 'numeric',
month: '2-digit'
}) : date.toDateString();
// case 'week':
// TODO
default:
return (date.toLocaleString || date.toString).call(date);
}
}
/**
* patch String.length to account for non-BMP characters
*
* @see https://mathiasbynens.be/notes/javascript-unicode
* We do not use the simple [...str].length, because it needs a ton of
* polyfills in older browsers.
*/
function unicode_string_length (str) {
return str.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g).length;
}
/**
* internal storage for custom error messages
*/
var store$1 = new WeakMap();
/**
* register custom error messages per element
*/
var custom_messages = {
set: function set(element, validator, message) {
var messages = store$1.get(element) || {};
messages[validator] = message;
store$1.set(element, messages);
return custom_messages;
},
get: function get(element, validator) {
var _default = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
var messages = store$1.get(element);
if (messages === undefined || !(validator in messages)) {
var data_id = 'data-' + validator.replace(/[A-Z]/g, '-$&').toLowerCase();
if (element.hasAttribute(data_id)) {
/* if the element has a data-validator attribute, use this as fallback.
* E.g., if validator == 'valueMissing', the element can specify a
* custom validation message like this:
* <input data-value-missing="Oh noes!">
*/
return element.getAttribute(data_id);
}
return _default;
}
return messages[validator];
},
delete: function _delete(element) {
var validator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (!validator) {
return store$1.delete(element);
}
var messages = store$1.get(element) || {};
if (validator in messages) {
delete messages[validator];
store$1.set(element, messages);
return true;
}
return false;
}
};
var internal_registry = new WeakMap();
/**
* A registry for custom validators
*
* slim wrapper around a WeakMap to ensure the values are arrays
* (hence allowing > 1 validators per element)
*/
var custom_validator_registry = {
set: function set(element, validator) {
var current = internal_registry.get(element) || [];
current.push(validator);
internal_registry.set(element, current);
return custom_validator_registry;
},
get: function get(element) {
return internal_registry.get(element) || [];
},
delete: function _delete(element) {
return internal_registry.delete(element);
}
};
/**
* test whether the element suffers from bad input
*/
function test_bad_input (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || input_checked.indexOf(type) === -1) {
/* we're not interested, thanks! */
return true;
}
/* the browser hides some bad input from the DOM, e.g. malformed numbers,
* email addresses with invalid punycode representation, ... We try to resort
* to the original method here. The assumption is, that a browser hiding
* bad input will hopefully also always support a proper
* ValidityState.badInput */
if (!element.value) {
if ('_original_validity' in element && !element._original_validity.__hyperform) {
return !element._original_validity.badInput;
}
/* no value and no original badInput: Assume all's right. */
return true;
}
var result = true;
switch (type) {
case 'color':
result = /^#[a-f0-9]{6}$/.test(element.value);
break;
case 'number':
case 'range':
result = !isNaN(Number(element.value));
break;
case 'datetime':
case 'date':
case 'month':
case 'week':
case 'time':
result = string_to_date(element.value, type) !== null;
break;
case 'datetime-local':
result = /^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(element.value);
break;
case 'tel':
/* spec says No! Phone numbers can have all kinds of formats, so this
* is expected to be a free-text field. */
// TODO we could allow a setting 'phone_regex' to be evaluated here.
break;
case 'email':
break;
}
return result;
}
/**
* test the max attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_max (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('max')) {
/* we're not responsible here */
return true;
}
var value = void 0,
max = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
max = 1 * (string_to_date(element.getAttribute('max'), type) || NaN);
} else {
value = Number(element.value);
max = Number(element.getAttribute('max'));
}
return isNaN(max) || value <= max;
}
/**
* test the maxlength attribute
*/
function test_maxlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('maxlength') || !element.getAttribute('maxlength') // catch maxlength=""
) {
return true;
}
var maxlength = parseInt(element.getAttribute('maxlength'), 10);
/* check, if the maxlength value is usable at all.
* We allow maxlength === 0 to basically disable input (Firefox does, too).
*/
if (isNaN(maxlength) || maxlength < 0) {
return true;
}
return unicode_string_length(element.value) <= maxlength;
}
/**
* test the min attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_min (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('min')) {
/* we're not responsible here */
return true;
}
var value = void 0,
min = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
min = 1 * (string_to_date(element.getAttribute('min'), type) || NaN);
} else {
value = Number(element.value);
min = Number(element.getAttribute('min'));
}
return isNaN(min) || value >= min;
}
/**
* test the minlength attribute
*/
function test_minlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('minlength') || !element.getAttribute('minlength') // catch minlength=""
) {
return true;
}
var minlength = parseInt(element.getAttribute('minlength'), 10);
/* check, if the minlength value is usable at all. */
if (isNaN(minlength) || minlength < 0) {
return true;
}
return unicode_string_length(element.value) >= minlength;
}
/**
* test the pattern attribute
*/
function test_pattern (element) {
return !is_validation_candidate(element) || !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value);
}
/**
* test the required attribute
*/
function test_required (element) {
if (!is_validation_candidate(element) || !element.hasAttribute('required')) {
/* nothing to do */
return true;
}
/* we don't need get_type() for element.type, because "checkbox" and "radio"
* are well supported. */
switch (element.type) {
case 'checkbox':
return element.checked;
//break;
case 'radio':
/* radio inputs have "required" fulfilled, if _any_ other radio
* with the same name in this form is checked. */
return !!(element.checked || element.form && Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form && radio.checked;
}).length > 0);
//break;
default:
return !!element.value;
}
}
/**
* test the step attribute
*/
function test_step (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || numbers.indexOf(type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') {
/* we're not responsible here. Note: If no step attribute is given, we
* need to validate against the default step as per spec. */
return true;
}
var step = element.getAttribute('step');
if (step) {
step = string_to_number(step, type);
} else {
step = default_step[type] || 1;
}
if (step <= 0 || isNaN(step)) {
/* error in specified "step". We cannot validate against it, so the value
* is true. */
return true;
}
var scale = step_scale_factor[type] || 1;
var value = string_to_number(element.value, type);
var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', type);
if (isNaN(min)) {
min = default_step_base[type] || 0;
}
if (type === 'month') {
/* type=month has month-wide steps. See
* https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29
*/
min = new Date(min).getUTCFullYear() * 12 + new Date(min).getUTCMonth();
value = new Date(value).getUTCFullYear() * 12 + new Date(value).getUTCMonth();
}
var result = Math.abs(min - value) % (step * scale);
return result < 0.00000001 ||
/* crappy floating-point arithmetics! */
result > step * scale - 0.00000001;
}
var ws_on_start_or_end = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
/**
* trim a string of whitespace
*
* We don't use String.trim() to remove the need to polyfill it.
*/
function trim (str) {
return str.replace(ws_on_start_or_end, '');
}
/**
* split a string on comma and trim the components
*
* As specified at
* https://html.spec.whatwg.org/multipage/infrastructure.html#split-a-string-on-commas
* plus removing empty entries.
*/
function comma_split (str) {
return str.split(',').map(function (item) {
return trim(item);
}).filter(function (b) {
return b;
});
}
/* we use a dummy <a> where we set the href to test URL validity
* The definition is out of the "global" scope so that JSDOM can be instantiated
* after loading Hyperform for tests.
*/
var url_canary;
/* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */
var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
* test the type-inherent syntax
*/
function test_type (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || type !== 'file' && !element.value || type !== 'file' && type_checked.indexOf(type) === -1) {
/* we're not responsible for this element */
return true;
}
var is_valid = true;
switch (type) {
case 'url':
if (!url_canary) {
url_canary = document.createElement('a');
}
var value = trim(element.value);
url_canary.href = value;
is_valid = url_canary.href === value || url_canary.href === value + '/';
break;
case 'email':
if (element.hasAttribute('multiple')) {
is_valid = comma_split(element.value).every(function (value) {
return email_pattern.test(value);
});
} else {
is_valid = email_pattern.test(trim(element.value));
}
break;
case 'file':
if ('files' in element && element.files.length && element.hasAttribute('accept')) {
var patterns = comma_split(element.getAttribute('accept')).map(function (pattern) {
if (/^(audio|video|image)\/\*$/.test(pattern)) {
pattern = new RegExp('^' + RegExp.$1 + '/.+$');
}
return pattern;
});
if (!patterns.length) {
break;
}
fileloop: for (var i = 0; i < element.files.length; i++) {
/* we need to match a whitelist, so pre-set with false */
var file_valid = false;
patternloop: for (var j = 0; j < patterns.length; j++) {
var file = element.files[i];
var pattern = patterns[j];
var fileprop = file.type;
if (typeof pattern === 'string' && pattern.substr(0, 1) === '.') {
if (file.name.search('.') === -1) {
/* no match with any file ending */
continue patternloop;
}
fileprop = file.name.substr(file.name.lastIndexOf('.'));
}
if (fileprop.search(pattern) === 0) {
/* we found one match and can quit looking */
file_valid = true;
break patternloop;
}
}
if (!file_valid) {
is_valid = false;
break fileloop;
}
}
}
}
return is_valid;
}
/**
* boilerplate function for all tests but customError
*/
function check$1(test, react) {
return function (element) {
var invalid = !test(element);
if (invalid) {
react(element);
}
return invalid;
};
}
/**
* create a common function to set error messages
*/
function set_msg(element, msgtype, _default) {
message_store.set(element, custom_messages.get(element, msgtype, _default));
}
var badInput = check$1(test_bad_input, function (element) {
return set_msg(element, 'badInput', _('Please match the requested type.'));
});
function customError(element) {
/* check, if there are custom validators in the registry, and call
* them. */
var custom_validators = custom_validator_registry.get(element);
var cvl = custom_validators.length;
var valid = true;
if (cvl) {
for (var i = 0; i < cvl; i++) {
var result = custom_validators[i](element);
if (result !== undefined && !result) {
valid = false;
/* break on first invalid response */
break;
}
}
}
/* check, if there are other validity messages already */
if (valid) {
var msg = message_store.get(element);
valid = !(msg.toString() && 'is_custom' in msg);
}
return !valid;
}
var patternMismatch = check$1(test_pattern, function (element) {
set_msg(element, 'patternMismatch', element.title ? sprintf(_('PatternMismatchWithTitle'), element.title) : _('PatternMismatch'));
});
/**
* TODO: when rangeOverflow and rangeUnderflow are both called directly and
* successful, the inRange and outOfRange classes won't get removed, unless
* element.validityState.valid is queried, too.
*/
var rangeOverflow = check$1(test_max, function (element) {
var type = get_type(element);
var wrapper = get_wrapper(element);
var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range';
var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range';
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type));
break;
case 'time':
msg = sprintf(_('TimeRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeOverflow'), string_to_number(element.getAttribute('max'), type));
break;
}
set_msg(element, 'rangeOverflow', msg);
element.classList.add(outOfRangeClass);
element.classList.remove(inRangeClass);
});
var rangeUnderflow = check$1(test_min, function (element) {
var type = get_type(element);
var wrapper = get_wrapper(element);
var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range';
var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range';
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type));
break;
case 'time':
msg = sprintf(_('TimeRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeUnderflow'), string_to_number(element.getAttribute('min'), type));
break;
}
set_msg(element, 'rangeUnderflow', msg);
element.classList.add(outOfRangeClass);
element.classList.remove(inRangeClass);
});
var stepMismatch = check$1(test_step, function (element) {
var list = get_next_valid(element);
var min = list[0];
var max = list[1];
var sole = false;
var msg = void 0;
if (min === null) {
sole = max;
} else if (max === null) {
sole = min;
}
if (sole !== false) {
msg = sprintf(_('StepMismatchOneValue'), sole);
} else {
msg = sprintf(_('StepMismatch'), min, max);
}
set_msg(element, 'stepMismatch', msg);
});
var tooLong = check$1(test_maxlength, function (element) {
set_msg(element, 'tooLong', sprintf(_('TextTooLong'), element.getAttribute('maxlength'), unicode_string_length(element.value)));
});
var tooShort = check$1(test_minlength, function (element) {
set_msg(element, 'tooShort', sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('minlength'), unicode_string_length(element.value)));
});
var typeMismatch = check$1(test_type, function (element) {
var msg = _('Please use the appropriate format.');
var type = get_type(element);
if (type === 'email') {
if (element.hasAttribute('multiple')) {
msg = _('Please enter a comma separated list of email addresses.');
} else {
msg = _('InvalidEmail');
}
} else if (type === 'url') {
msg = _('InvalidURL');
} else if (type === 'file') {
msg = _('Please select a file of the correct type.');
}
set_msg(element, 'typeMismatch', msg);
});
var valueMissing = check$1(test_required, function (element) {
var msg = _('ValueMissing');
var type = get_type(element);
if (type === 'checkbox') {
msg = _('CheckboxMissing');
} else if (type === 'radio') {
msg = _('RadioMissing');
} else if (type === 'file') {
if (element.hasAttribute('multiple')) {
msg = _('Please select one or more files.');
} else {
msg = _('FileMissing');
}
} else if (element instanceof window.HTMLSelectElement) {
msg = _('SelectMissing');
}
set_msg(element, 'valueMissing', msg);
});
var validity_state_checkers = {
badInput: badInput,
customError: customError,
patternMismatch: patternMismatch,
rangeOverflow: rangeOverflow,
rangeUnderflow: rangeUnderflow,
stepMismatch: stepMismatch,
tooLong: tooLong,
tooShort: tooShort,
typeMismatch: typeMismatch,
valueMissing: valueMissing
};
/**
* the validity state constructor
*/
var ValidityState = function ValidityState(element) {
if (!(element instanceof window.HTMLElement)) {
throw new Error('cannot create a ValidityState for a non-element');
}
var cached = ValidityState.cache.get(element);
if (cached) {
return cached;
}
if (!(this instanceof ValidityState)) {
/* working around a forgotten `new` */
return new ValidityState(element);
}
this.element = element;
ValidityState.cache.set(element, this);
};
/**
* the prototype for new validityState instances
*/
var ValidityStatePrototype = {};
ValidityState.prototype = ValidityStatePrototype;
ValidityState.cache = new WeakMap();
/**
* copy functionality from the validity checkers to the ValidityState
* prototype
*/
for (var prop in validity_state_checkers) {
Object.defineProperty(ValidityStatePrototype, prop, {
configurable: true,
enumerable: true,
get: function (func) {
return function () {
return func(this.element);
};
}(validity_state_checkers[prop]),
set: undefined
});
}
/**
* the "valid" property calls all other validity checkers and returns true,
* if all those return false.
*
* This is the major access point for _all_ other API methods, namely
* (check|report)Validity().
*/
Object.defineProperty(ValidityStatePrototype, 'valid', {
configurable: true,
enumerable: true,
get: function get() {
var wrapper = get_wrapper(this.element);
var validClass = wrapper && wrapper.settings.classes.valid || 'hf-valid';
var invalidClass = wrapper && wrapper.settings.classes.invalid || 'hf-invalid';
var userInvalidClass = wrapper && wrapper.settings.classes.userInvalid || 'hf-user-invalid';
var userValidClass = wrapper && wrapper.settings.classes.userValid || 'hf-user-valid';
var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range';
var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range';
var validatedClass = wrapper && wrapper.settings.classes.validated || 'hf-validated';
this.element.classList.add(validatedClass);
if (is_validation_candidate(this.element)) {
for (var _prop in validity_state_checkers) {
if (validity_state_checkers[_prop](this.element)) {
this.element.classList.add(invalidClass);
this.element.classList.remove(validClass);
this.element.classList.remove(userValidClass);
if (this.element.value !== this.element.defaultValue) {
this.element.classList.add(userInvalidClass);
} else {
this.element.classList.remove(userInvalidClass);
}
this.element.setAttribute('aria-invalid', 'true');
return false;
}
}
}
message_store.delete(this.element);
this.element.classList.remove(invalidClass, userInvalidClass, outOfRangeClass);
this.element.classList.add(validClass, inRangeClass);
if (this.element.value !== this.element.defaultValue) {
this.element.classList.add(userValidClass);
} else {
this.element.classList.remove(userValidClass);
}
this.element.setAttribute('aria-invalid', 'false');
return true;
},
set: undefined
});
/**
* mark the validity prototype, because that is what the client-facing
* code deals with mostly, not the property descriptor thing */
mark(ValidityStatePrototype);
/**
* check an element's validity with respect to it's form
*/
var checkValidity = return_hook_or('checkValidity', function (element) {
/* if this is a <form>, check validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, checkValidity).every(function (b) {
return b;
});
}
/* default is true, also for elements that are no validation candidates */
var valid = ValidityState(element).valid;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.validEvent) {
trigger_event(element, 'valid');
}
} else {
trigger_event(element, 'invalid', { cancelable: true });
}
return valid;
});
var version = '0.9.2';
/* deprecate the old snake_case names
* TODO: delme before next non-patch release
*/
function w(name) {
var deprecated_message = 'Please use camelCase method names! The name "%s" is deprecated and will be removed in the next non-patch release.';
/* global console */
console.log(sprintf(deprecated_message, name));
}
/**
* public hyperform interface:
*/
function hyperform(form) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var classes = _ref.classes;
var _ref$debug = _ref.debug;
var debug = _ref$debug === undefined ? false : _ref$debug;
var extend_fieldset = _ref.extend_fieldset;
var extendFieldset = _ref.extendFieldset;
var novalidate_on_elements = _ref.novalidate_on_elements;
var novalidateOnElements = _ref.novalidateOnElements;
var prevent_implicit_submit = _ref.prevent_implicit_submit;
var preventImplicitSubmit = _ref.preventImplicitSubmit;
var revalidate = _ref.revalidate;
var _ref$strict = _ref.strict;
var strict = _ref$strict === undefined ? false : _ref$strict;
var valid_event = _ref.valid_event;
var validEvent = _ref.validEvent;
if (!classes) {
classes = {};
}
// TODO: clean up before next non-patch release
if (extendFieldset === undefined) {
if (extend_fieldset === undefined) {
extendFieldset = !strict;
} else {
w('extend_fieldset');
extendFieldset = extend_fieldset;
}
}
if (novalidateOnElements === undefined) {
if (novalidate_on_elements === undefined) {
novalidateOnElements = !strict;
} else {
w('novalidate_on_elements');
novalidateOnElements = novalidate_on_elements;
}
}
if (preventImplicitSubmit === undefined) {
if (prevent_implicit_submit === undefined) {
preventImplicitSubmit = false;
} else {
w('prevent_implicit_submit');
preventImplicitSubmit = prevent_implicit_submit;
}
}
if (revalidate === undefined) {
/* other recognized values: 'oninput', 'onblur', 'onsubmit' and 'never' */
revalidate = strict ? 'onsubmit' : 'hybrid';
}
if (validEvent === undefined) {
if (valid_event === undefined) {
validEvent = !strict;
} else {
w('valid_event');
validEvent = valid_event;
}
}
var settings = { debug: debug, strict: strict, preventImplicitSubmit: preventImplicitSubmit, revalidate: revalidate,
validEvent: validEvent, extendFieldset: extendFieldset, classes: classes };
if (form instanceof window.NodeList || form instanceof window.HTMLCollection || form instanceof Array) {
return Array.prototype.map.call(form, function (element) {
return hyperform(element, settings);
});
}
return new Wrapper(form, settings);
}
hyperform.version = version;
hyperform.checkValidity = checkValidity;
hyperform.reportValidity = reportValidity;
hyperform.setCustomValidity = setCustomValidity;
hyperform.stepDown = stepDown;
hyperform.stepUp = stepUp;
hyperform.validationMessage = validationMessage;
hyperform.ValidityState = ValidityState;
hyperform.valueAsDate = valueAsDate;
hyperform.valueAsNumber = valueAsNumber;
hyperform.willValidate = willValidate;
hyperform.setLanguage = function (lang) {
set_language(lang);return hyperform;
};
hyperform.addTranslation = function (lang, catalog) {
add_translation(lang, catalog);return hyperform;
};
hyperform.setRenderer = function (renderer, action) {
Renderer.set(renderer, action);return hyperform;
};
hyperform.addValidator = function (element, validator) {
custom_validator_registry.set(element, validator);return hyperform;
};
hyperform.setMessage = function (element, validator, message) {
custom_messages.set(element, validator, message);return hyperform;
};
hyperform.addHook = function (hook, action, position) {
add_hook(hook, action, position);return hyperform;
};
hyperform.removeHook = function (hook, action) {
remove_hook(hook, action);return hyperform;
};
// TODO: Remove in next non-patch version
hyperform.set_language = function (lang) {
w('set_language');set_language(lang);return hyperform;
};
hyperform.add_translation = function (lang, catalog) {
w('add_translation');add_translation(lang, catalog);return hyperform;
};
hyperform.set_renderer = function (renderer, action) {
w('set_renderer');Renderer.set(renderer, action);return hyperform;
};
hyperform.add_validator = function (element, validator) {
w('add_validator');custom_validator_registry.set(element, validator);return hyperform;
};
hyperform.set_message = function (element, validator, message) {
w('set_message');custom_messages.set(element, validator, message);return hyperform;
};
hyperform.add_hook = function (hook, action, position) {
w('add_hook');add_hook(hook, action, position);return hyperform;
};
hyperform.remove_hook = function (hook, action) {
w('remove_hook');remove_hook(hook, action);return hyperform;
};
return hyperform;
}); |
src/components/imageListManage/ImageListManage.js | numb86/image-editor | // @flow
import React from 'react';
import ImageListManageItem from './ImageListManageItem';
import {
generateImageList,
SPECIFY_IMAGE_PROPERTY,
SPECIFY_ACTIVE_IMAGE,
ADD_NEW_IMAGE,
DELETE_IMAGE,
MOVE_UP_IMAGE_ORDER,
} from '../../state/generateImageList';
import type {Image} from '../../image';
export default function ImageListManage({
imageList,
updateImageList,
display,
}: {
imageList: Image[],
updateImageList: (Image[]) => void,
display: {width: number, height: number},
}) {
return (
<ul className="image-list-manage">
<li>
<button
className="add-new-image fa fa-plus"
onClick={() => {
updateImageList(
generateImageList({
type: ADD_NEW_IMAGE,
currentState: imageList,
data: {width: display.width, height: display.height},
})
);
}}
/>
</li>
{imageList.map((image, index) => (
<ImageListManageItem
key={image.id}
deleteImage={
imageList.length === 1
? null
: () => {
updateImageList(
generateImageList({
type: DELETE_IMAGE,
currentState: imageList,
target: image.id,
})
);
}
}
label={image.label}
isActive={image.isActive}
isShow={image.isShow}
activate={() => {
updateImageList(
generateImageList({
type: SPECIFY_ACTIVE_IMAGE,
currentState: imageList,
target: image.id,
})
);
}}
moveUpImageOrder={
index === 0
? null
: () => {
updateImageList(
generateImageList({
type: MOVE_UP_IMAGE_ORDER,
currentState: imageList,
target: image.id,
})
);
}
}
moveDownImageOrder={
index === imageList.length - 1
? null
: () => {
updateImageList(
generateImageList({
type: MOVE_UP_IMAGE_ORDER,
currentState: imageList,
target: imageList[index + 1].id,
})
);
}
}
toggleShowOrHide={() => {
updateImageList(
generateImageList({
type: SPECIFY_IMAGE_PROPERTY,
data: {isShow: !image.isShow},
currentState: imageList,
target: image.id,
})
);
}}
/>
))}
</ul>
);
}
|
node_modules/react-bootstrap/es/SplitToggle.js | hsavit1/gosofi_webpage | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import DropdownToggle from './DropdownToggle';
var SplitToggle = function (_React$Component) {
_inherits(SplitToggle, _React$Component);
function SplitToggle() {
_classCallCheck(this, SplitToggle);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
SplitToggle.prototype.render = function render() {
return React.createElement(DropdownToggle, _extends({}, this.props, {
useAnchor: false,
noCaret: false
}));
};
return SplitToggle;
}(React.Component);
SplitToggle.defaultProps = DropdownToggle.defaultProps;
export default SplitToggle; |
ajax/libs/yui/3.4.0pr1/loader/loader.js | Amomo/cdnjs | YUI.add('loader-base', function(Y) {
/**
* The YUI loader core
* @module loader
* @submodule loader-base
*/
if (!YUI.Env[Y.version]) {
(function() {
var VERSION = Y.version,
BUILD = '/build/',
ROOT = VERSION + BUILD,
CDN_BASE = Y.Env.base,
GALLERY_VERSION = 'gallery-2011.04.13-22-38',
TNT = '2in3',
TNT_VERSION = '4',
YUI2_VERSION = '2.9.0',
COMBO_BASE = CDN_BASE + 'combo?',
META = { version: VERSION,
root: ROOT,
base: Y.Env.base,
comboBase: COMBO_BASE,
skin: { defaultSkin: 'sam',
base: 'assets/skins/',
path: 'skin.css',
after: ['cssreset',
'cssfonts',
'cssgrids',
'cssbase',
'cssreset-context',
'cssfonts-context']},
groups: {},
patterns: {} },
groups = META.groups,
yui2Update = function(tnt, yui2) {
var root = TNT + '.' +
(tnt || TNT_VERSION) + '/' +
(yui2 || YUI2_VERSION) + BUILD;
groups.yui2.base = CDN_BASE + root;
groups.yui2.root = root;
},
galleryUpdate = function(tag) {
var root = (tag || GALLERY_VERSION) + BUILD;
groups.gallery.base = CDN_BASE + root;
groups.gallery.root = root;
};
groups[VERSION] = {};
groups.gallery = {
ext: false,
combine: true,
comboBase: COMBO_BASE,
update: galleryUpdate,
patterns: { 'gallery-': { },
'gallerycss-': { type: 'css' } }
};
groups.yui2 = {
combine: true,
ext: false,
comboBase: COMBO_BASE,
update: yui2Update,
patterns: {
'yui2-': {
configFn: function(me) {
if (/-skin|reset|fonts|grids|base/.test(me.name)) {
me.type = 'css';
me.path = me.path.replace(/\.js/, '.css');
// this makes skins in builds earlier than
// 2.6.0 work as long as combine is false
me.path = me.path.replace(/\/yui2-skin/,
'/assets/skins/sam/yui2-skin');
}
}
}
}
};
galleryUpdate();
yui2Update();
YUI.Env[VERSION] = META;
}());
}
/**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
*
* @module loader
* @submodule loader-base
*/
var NOT_FOUND = {},
NO_REQUIREMENTS = [],
MAX_URL_LENGTH = (Y.UA.ie) ? 2048 : 8192,
GLOBAL_ENV = YUI.Env,
GLOBAL_LOADED = GLOBAL_ENV._loaded,
CSS = 'css',
JS = 'js',
INTL = 'intl',
VERSION = Y.version,
ROOT_LANG = '',
YObject = Y.Object,
oeach = YObject.each,
YArray = Y.Array,
_queue = GLOBAL_ENV._loaderQueue,
META = GLOBAL_ENV[VERSION],
SKIN_PREFIX = 'skin-',
L = Y.Lang,
ON_PAGE = GLOBAL_ENV.mods,
modulekey,
cache,
_path = function(dir, file, type, nomin) {
var path = dir + '/' + file;
if (!nomin) {
path += '-min';
}
path += '.' + (type || CSS);
return path;
};
/**
* The component metadata is stored in Y.Env.meta.
* Part of the loader module.
* @property Env.meta
* @for YUI
*/
Y.Env.meta = META;
/**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
*
* While the loader can be instantiated by the end user, it normally is not.
* @see YUI.use for the normal use case. The use function automatically will
* pull in missing dependencies.
*
* @constructor
* @class Loader
* @param {object} o an optional set of configuration options. Valid options:
* <ul>
* <li>base:
* The base dir</li>
* <li>comboBase:
* The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li>
* <li>root:
* The root path to prepend to module names for the combo service.
* Ex: 2.5.2/build/</li>
* <li>filter:.
*
* 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:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
*
* </li>
* <li>filters: per-component filter specification. If specified
* for a given component, this overrides the filter config</li>
* <li>combine:
* Use the YUI combo service to reduce the number of http connections
* required to load your dependencies</li>
* <li>ignore:
* A list of modules that should never be dynamically loaded</li>
* <li>force:
* A list of modules that should always be loaded when required, even if
* already present on the page</li>
* <li>insertBefore:
* Node or id for a node that should be used as the insertion point for
* new nodes</li>
* <li>charset:
* charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes)
* </li>
* <li>jsAttributes: object literal containing attributes to add to script
* nodes</li>
* <li>cssAttributes: object literal containing attributes to add to link
* nodes</li>
* <li>timeout:
* The number of milliseconds before a timeout occurs when dynamically
* loading nodes. If not set, there is no timeout</li>
* <li>context:
* execution context for all callbacks</li>
* <li>onSuccess:
* callback for the 'success' event</li>
* <li>onFailure: callback for the 'failure' event</li>
* <li>onCSS: callback for the 'CSSComplete' event. When loading YUI
* components with CSS the CSS is loaded first, then the script. This
* provides a moment you can tie into to improve
* the presentation of the page while the script is loading.</li>
* <li>onTimeout:
* callback for the 'timeout' event</li>
* <li>onProgress:
* callback executed each time a script or css file is loaded</li>
* <li>modules:
* A list of module definitions. See Loader.addModule for the supported
* module metadata</li>
* <li>groups:
* A list of group definitions. Each group can contain specific definitions
* for base, comboBase, combine, and accepts a list of modules. See above
* for the description of these properties.</li>
* <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic
* support for YUI 2 modules in YUI 3 relies on versions of the YUI 2
* components inside YUI 3 module wrappers. These wrappers
* change over time to accomodate the issues that arise from running YUI 2
* in a YUI 3 sandbox.</li>
* <li>yui2: when using the 2in3 project, you can select the version of
* YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0,
* 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2
* going forward.</li>
* </ul>
*/
Y.Loader = function(o) {
var defaults = META.modules,
self = this;
modulekey = META.md5;
/**
* Internal callback to handle multiple internal insert() calls
* so that css is inserted prior to js
* @property _internalCallback
* @private
*/
// self._internalCallback = null;
/**
* Callback that will be executed when the loader is finished
* with an insert
* @method onSuccess
* @type function
*/
// self.onSuccess = null;
/**
* Callback that will be executed if there is a failure
* @method onFailure
* @type function
*/
// self.onFailure = null;
/**
* Callback for the 'CSSComplete' event. When loading YUI components
* with CSS the CSS is loaded first, then the script. This provides
* a moment you can tie into to improve the presentation of the page
* while the script is loading.
* @method onCSS
* @type function
*/
// self.onCSS = null;
/**
* Callback executed each time a script or css file is loaded
* @method onProgress
* @type function
*/
// self.onProgress = null;
/**
* Callback that will be executed if a timeout occurs
* @method onTimeout
* @type function
*/
// self.onTimeout = null;
/**
* The execution context for all callbacks
* @property context
* @default {YUI} the YUI instance
*/
self.context = Y;
/**
* Data that is passed to all callbacks
* @property data
*/
// self.data = null;
/**
* Node reference or id where new nodes should be inserted before
* @property insertBefore
* @type string|HTMLElement
*/
// self.insertBefore = null;
/**
* The charset attribute for inserted nodes
* @property charset
* @type string
* @deprecated , use cssAttributes or jsAttributes.
*/
// self.charset = null;
/**
* An object literal containing attributes to add to link nodes
* @property cssAttributes
* @type object
*/
// self.cssAttributes = null;
/**
* An object literal containing attributes to add to script nodes
* @property jsAttributes
* @type object
*/
// self.jsAttributes = null;
/**
* The base directory.
* @property base
* @type string
* @default http://yui.yahooapis.com/[YUI VERSION]/build/
*/
self.base = Y.Env.meta.base;
/**
* Base path for the combo service
* @property comboBase
* @type string
* @default http://yui.yahooapis.com/combo?
*/
self.comboBase = Y.Env.meta.comboBase;
/*
* Base path for language packs.
*/
// self.langBase = Y.Env.meta.langBase;
// self.lang = "";
/**
* If configured, the loader will attempt to use the combo
* service for YUI resources and configured external resources.
* @property combine
* @type boolean
* @default true if a base dir isn't in the config
*/
self.combine = o.base &&
(o.base.indexOf(self.comboBase.substr(0, 20)) > -1);
/**
* Max url length for combo urls. The default is 2048 for
* internet explorer, and 8192 otherwise. This is the URL
* limit for the Yahoo! hosted combo servers. If consuming
* a different combo service that has a different URL limit
* it is possible to override this default by supplying
* the maxURLLength config option. The config option will
* only take effect if lower than the default.
*
* Browsers:
* IE: 2048
* Other A-Grade Browsers: Higher that what is typically supported
* 'capable' mobile browsers:
*
* Servers:
* Apache: 8192
*
* @property maxURLLength
* @type int
*/
self.maxURLLength = MAX_URL_LENGTH;
/**
* Ignore modules registered on the YUI global
* @property ignoreRegistered
* @default false
*/
// self.ignoreRegistered = false;
/**
* Root path to prepend to module path for the combo
* service
* @property root
* @type string
* @default [YUI VERSION]/build/
*/
self.root = Y.Env.meta.root;
/**
* Timeout value in milliseconds. If set, self value will be used by
* the get utility. the timeout event will fire if
* a timeout occurs.
* @property timeout
* @type int
*/
self.timeout = 0;
/**
* A list of modules that should not be loaded, even if
* they turn up in the dependency tree
* @property ignore
* @type string[]
*/
// self.ignore = null;
/**
* A list of modules that should always be loaded, even
* if they have already been inserted into the page.
* @property force
* @type string[]
*/
// self.force = null;
self.forceMap = {};
/**
* Should we allow rollups
* @property allowRollup
* @type boolean
* @default true
*/
self.allowRollup = true;
/**
* 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:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
* @property filter
* @type string| {searchExp: string, replaceStr: string}
*/
// self.filter = null;
/**
* per-component filter specification. If specified for a given
* component, this overrides the filter config.
* @property filters
* @type object
*/
self.filters = {};
/**
* The list of requested modules
* @property required
* @type {string: boolean}
*/
self.required = {};
/**
* If a module name is predefined when requested, it is checked againsts
* the patterns provided in this property. If there is a match, the
* module is added with the default configuration.
*
* At the moment only supporting module prefixes, but anticipate
* supporting at least regular expressions.
* @property patterns
* @type Object
*/
// self.patterns = Y.merge(Y.Env.meta.patterns);
self.patterns = {};
/**
* The library metadata
* @property moduleInfo
*/
// self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo);
self.moduleInfo = {};
self.groups = Y.merge(Y.Env.meta.groups);
/**
* Provides the information used to skin the skinnable components.
* The following skin definition would result in 'skin1' and 'skin2'
* being loaded for calendar (if calendar was requested), and
* 'sam' for all other skinnable components:
*
* <code>
* skin: {
*
* // 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. ex:
* // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/
* 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: {
* calendar: ['skin1', 'skin2']
* }
* }
* </code>
* @property skin
*/
self.skin = Y.merge(Y.Env.meta.skin);
/*
* Map of conditional modules
* @since 3.2.0
*/
self.conditions = {};
// map of modules with a hash of modules that meet the requirement
// self.provides = {};
self.config = o;
self._internal = true;
cache = GLOBAL_ENV._renderedMods;
if (cache) {
oeach(cache, function(v, k) {
self.moduleInfo[k] = Y.merge(v);
});
cache = GLOBAL_ENV._conditions;
oeach(cache, function(v, k) {
self.conditions[k] = Y.merge(v);
});
} else {
oeach(defaults, self.addModule, self);
}
if (!GLOBAL_ENV._renderedMods) {
GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo);
GLOBAL_ENV._conditions = Y.merge(self.conditions);
}
self._inspectPage();
self._internal = false;
self._config(o);
/**
* List of rollup files found in the library metadata
* @property rollups
*/
// self.rollups = null;
/**
* Whether or not to load optional dependencies for
* the requested modules
* @property loadOptional
* @type boolean
* @default false
*/
// self.loadOptional = false;
/**
* All of the derived dependencies in sorted order, which
* will be populated when either calculate() or insert()
* is called
* @property sorted
* @type string[]
*/
self.sorted = [];
/**
* Set when beginning to compute the dependency tree.
* Composed of what YUI reports to be loaded combined
* with what has been loaded by any instance on the page
* with the version number specified in the metadata.
* @property loaded
* @type {string: boolean}
*/
self.loaded = GLOBAL_LOADED[VERSION];
/*
* A list of modules to attach to the YUI instance when complete.
* If not supplied, the sorted list of dependencies are applied.
* @property attaching
*/
// self.attaching = null;
/**
* Flag to indicate the dependency tree needs to be recomputed
* if insert is called again.
* @property dirty
* @type boolean
* @default true
*/
self.dirty = true;
/**
* List of modules inserted by the utility
* @property inserted
* @type {string: boolean}
*/
self.inserted = {};
/**
* List of skipped modules during insert() because the module
* was not defined
* @property skipped
*/
self.skipped = {};
// Y.on('yui:load', self.loadNext, self);
self.tested = {};
/*
* Cached sorted calculate results
* @property results
* @since 3.2.0
*/
//self.results = {};
};
Y.Loader.prototype = {
FILTER_DEFS: {
RAW: {
'searchExp': '-min\\.js',
'replaceStr': '.js'
},
DEBUG: {
'searchExp': '-min\\.js',
'replaceStr': '-debug.js'
}
},
_inspectPage: function() {
oeach(ON_PAGE, function(v, k) {
if (v.details) {
var m = this.moduleInfo[k],
req = v.details.requires,
mr = m && m.requires;
if (m) {
if (!m._inspected && req && mr.length != req.length) {
// console.log('deleting ' + m.name);
// m.requres = YObject.keys(Y.merge(YArray.hash(req), YArray.hash(mr)));
delete m.expanded;
// delete m.expanded_map;
}
} else {
m = this.addModule(v.details, k);
}
m._inspected = true;
}
}, this);
},
// returns true if b is not loaded, and is required
// directly or by means of modules it supersedes.
_requires: function(mod1, mod2) {
var i, rm, after_map, s,
info = this.moduleInfo,
m = info[mod1],
other = info[mod2];
if (!m || !other) {
return false;
}
rm = m.expanded_map;
after_map = m.after_map;
// check if this module should be sorted after the other
// do this first to short circut circular deps
if (after_map && (mod2 in after_map)) {
return true;
}
after_map = other.after_map;
// and vis-versa
if (after_map && (mod1 in after_map)) {
return false;
}
// check if this module requires one the other supersedes
s = info[mod2] && info[mod2].supersedes;
if (s) {
for (i = 0; i < s.length; i++) {
if (this._requires(mod1, s[i])) {
return true;
}
}
}
s = info[mod1] && info[mod1].supersedes;
if (s) {
for (i = 0; i < s.length; i++) {
if (this._requires(mod2, s[i])) {
return false;
}
}
}
// check if this module requires the other directly
// if (r && YArray.indexOf(r, mod2) > -1) {
if (rm && (mod2 in rm)) {
return true;
}
// external css files should be sorted below yui css
if (m.ext && m.type == CSS && !other.ext && other.type == CSS) {
return true;
}
return false;
},
_config: function(o) {
var i, j, val, f, group, groupName, self = this;
// apply config values
if (o) {
for (i in o) {
if (o.hasOwnProperty(i)) {
val = o[i];
if (i == 'require') {
self.require(val);
} else if (i == 'skin') {
Y.mix(self.skin, o[i], true);
} else if (i == 'groups') {
for (j in val) {
if (val.hasOwnProperty(j)) {
groupName = j;
group = val[j];
self.addGroup(group, groupName);
}
}
} else if (i == 'modules') {
// add a hash of module definitions
oeach(val, self.addModule, self);
} else if (i == 'gallery') {
this.groups.gallery.update(val);
} else if (i == 'yui2' || i == '2in3') {
this.groups.yui2.update(o['2in3'], o.yui2);
} else if (i == 'maxURLLength') {
self[i] = Math.min(MAX_URL_LENGTH, val);
} else {
self[i] = val;
}
}
}
}
// fix filter
f = self.filter;
if (L.isString(f)) {
f = f.toUpperCase();
self.filterName = f;
self.filter = self.FILTER_DEFS[f];
if (f == 'DEBUG') {
self.require('yui-log', 'dump');
}
}
},
/**
* Returns the skin module name for the specified skin name. If a
* module name is supplied, the returned skin module name is
* specific to the module passed in.
* @method formatSkin
* @param {string} skin the name of the skin.
* @param {string} mod optional: the name of a module to skin.
* @return {string} the full skin module name.
*/
formatSkin: function(skin, mod) {
var s = SKIN_PREFIX + skin;
if (mod) {
s = s + '-' + mod;
}
return s;
},
/**
* Adds the skin def to the module info
* @method _addSkin
* @param {string} skin the name of the skin.
* @param {string} mod the name of the module.
* @param {string} parent parent module if this is a skin of a
* submodule or plugin.
* @return {string} the module name for the skin.
* @private
*/
_addSkin: function(skin, mod, parent) {
var mdef, pkg, name,
info = this.moduleInfo,
sinf = this.skin,
ext = info[mod] && info[mod].ext;
// Add a module definition for the module-specific skin css
if (mod) {
name = this.formatSkin(skin, mod);
if (!info[name]) {
mdef = info[mod];
pkg = mdef.pkg || mod;
this.addModule({
name: name,
group: mdef.group,
type: 'css',
after: sinf.after,
path: (parent || pkg) + '/' + sinf.base + skin +
'/' + mod + '.css',
ext: ext
});
}
}
return name;
},
/**
* Add a new module group
* <dl>
* <dt>name:</dt> <dd>required, the group name</dd>
* <dt>base:</dt> <dd>The base dir for this module group</dd>
* <dt>root:</dt> <dd>The root path to add to each combo
* resource path</dd>
* <dt>combine:</dt> <dd>combo handle</dd>
* <dt>comboBase:</dt> <dd>combo service base path</dd>
* <dt>modules:</dt> <dd>the group of modules</dd>
* </dl>
* @method addGroup
* @param {object} o An object containing the module data.
* @param {string} name the group name.
*/
addGroup: function(o, name) {
var mods = o.modules,
self = this;
name = name || o.name;
o.name = name;
self.groups[name] = o;
if (o.patterns) {
oeach(o.patterns, function(v, k) {
v.group = name;
self.patterns[k] = v;
});
}
if (mods) {
oeach(mods, function(v, k) {
v.group = name;
self.addModule(v, k);
}, self);
}
},
/**
* Add a new module to the component metadata.
* <dl>
* <dt>name:</dt> <dd>required, the component name</dd>
* <dt>type:</dt> <dd>required, the component type (js or css)
* </dd>
* <dt>path:</dt> <dd>required, the path to the script from
* "base"</dd>
* <dt>requires:</dt> <dd>array of modules required by this
* component</dd>
* <dt>optional:</dt> <dd>array of optional modules for this
* component</dd>
* <dt>supersedes:</dt> <dd>array of the modules this component
* replaces</dd>
* <dt>after:</dt> <dd>array of modules the components which, if
* present, should be sorted above this one</dd>
* <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply
* a hash instead of an array</dd>
* <dt>rollup:</dt> <dd>the number of superseded modules required
* for automatic rollup</dd>
* <dt>fullpath:</dt> <dd>If fullpath is specified, this is used
* instead of the configured base + path</dd>
* <dt>skinnable:</dt> <dd>flag to determine if skin assets should
* automatically be pulled in</dd>
* <dt>submodules:</dt> <dd>a hash of submodules</dd>
* <dt>group:</dt> <dd>The group the module belongs to -- this
* is set automatically when it is added as part of a group
* configuration.</dd>
* <dt>lang:</dt>
* <dd>array of BCP 47 language tags of languages for which this
* module has localized resource bundles,
* e.g., ["en-GB","zh-Hans-CN"]</dd>
* <dt>condition:</dt>
* <dd>Specifies that the module should be loaded automatically if
* a condition is met. This is an object with up to three fields:
* [trigger] - the name of a module that can trigger the auto-load
* [test] - a function that returns true when the module is to be
* loaded.
* [when] - specifies the load order of the conditional module
* with regard to the position of the trigger module.
* This should be one of three values: 'before', 'after', or
* 'instead'. The default is 'after'.
* </dd>
* <dt>testresults:</dt><dd>a hash of test results from Y.Features.all()</dd>
* </dl>
* @method addModule
* @param {object} o An object containing the module data.
* @param {string} name the module name (optional), required if not
* in the module data.
* @return {object} the module definition or null if
* the object passed in did not provide all required attributes.
*/
addModule: function(o, name) {
name = name || o.name;
o.name = name;
if (!o || !o.name) {
return null;
}
if (!o.type) {
o.type = JS;
}
if (!o.path && !o.fullpath) {
o.path = _path(name, name, o.type);
}
o.supersedes = o.supersedes || o.use;
o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true;
o.requires = o.requires || [];
// Handle submodule logic
var subs = o.submodules, i, l, sup, s, smod, plugins, plug,
j, langs, packName, supName, flatSup, flatLang, lang, ret,
overrides, skinname, when,
conditions = this.conditions, trigger;
// , existing = this.moduleInfo[name], newr;
this.moduleInfo[name] = o;
if (!o.langPack && o.lang) {
langs = YArray(o.lang);
for (j = 0; j < langs.length; j++) {
lang = langs[j];
packName = this.getLangPackName(lang, name);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
}
}
if (subs) {
sup = o.supersedes || [];
l = 0;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
s.path = s.path || _path(name, i, o.type);
s.pkg = name;
s.group = o.group;
if (s.supersedes) {
sup = sup.concat(s.supersedes);
}
smod = this.addModule(s, i);
sup.push(i);
if (smod.skinnable) {
o.skinnable = true;
overrides = this.skin.overrides;
if (overrides && overrides[i]) {
for (j = 0; j < overrides[i].length; j++) {
skinname = this._addSkin(overrides[i][j],
i, name);
sup.push(skinname);
}
}
skinname = this._addSkin(this.skin.defaultSkin,
i, name);
sup.push(skinname);
}
// looks like we are expected to work out the metadata
// for the parent module language packs from what is
// specified in the child modules.
if (s.lang && s.lang.length) {
langs = YArray(s.lang);
for (j = 0; j < langs.length; j++) {
lang = langs[j];
packName = this.getLangPackName(lang, name);
supName = this.getLangPackName(lang, i);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
flatSup = flatSup || YArray.hash(smod.supersedes);
if (!(supName in flatSup)) {
smod.supersedes.push(supName);
}
o.lang = o.lang || [];
flatLang = flatLang || YArray.hash(o.lang);
if (!(lang in flatLang)) {
o.lang.push(lang);
}
// Add rollup file, need to add to supersedes list too
// default packages
packName = this.getLangPackName(ROOT_LANG, name);
supName = this.getLangPackName(ROOT_LANG, i);
smod = this.moduleInfo[packName];
if (!smod) {
smod = this._addLangPack(lang, o, packName);
}
if (!(supName in flatSup)) {
smod.supersedes.push(supName);
}
// Add rollup file, need to add to supersedes list too
}
}
l++;
}
}
o.supersedes = YObject.keys(YArray.hash(sup));
o.rollup = (l < 4) ? l : Math.min(l - 1, 4);
}
plugins = o.plugins;
if (plugins) {
for (i in plugins) {
if (plugins.hasOwnProperty(i)) {
plug = plugins[i];
plug.pkg = name;
plug.path = plug.path || _path(name, i, o.type);
plug.requires = plug.requires || [];
plug.group = o.group;
this.addModule(plug, i);
if (o.skinnable) {
this._addSkin(this.skin.defaultSkin, i, name);
}
}
}
}
if (o.condition) {
trigger = o.condition.trigger;
when = o.condition.when;
conditions[trigger] = conditions[trigger] || {};
conditions[trigger][name] = o.condition;
// the 'when' attribute can be 'before', 'after', or 'instead'
// the default is after.
if (when && when != 'after') {
if (when == 'instead') { // replace the trigger
o.supersedes = o.supersedes || [];
o.supersedes.push(trigger);
} else { // before the trigger
// the trigger requires the conditional mod,
// so it should appear before the conditional
// mod if we do not intersede.
}
} else { // after the trigger
o.after = o.after || [];
o.after.push(trigger);
}
}
if (o.after) {
o.after_map = YArray.hash(o.after);
}
// this.dirty = true;
if (o.configFn) {
ret = o.configFn(o);
if (ret === false) {
delete this.moduleInfo[name];
o = null;
}
}
return o;
},
/**
* Add a requirement for one or more module
* @method require
* @param {string[] | string*} what the modules to load.
*/
require: function(what) {
var a = (typeof what === 'string') ? arguments : what;
this.dirty = true;
Y.mix(this.required, YArray.hash(a));
},
/**
* Returns an object containing properties for all modules required
* in order to load the requested module
* @method getRequires
* @param {object} mod The module definition from moduleInfo.
* @return {array} the expanded requirement list.
*/
getRequires: function(mod) {
if (!mod || mod._parsed) {
return NO_REQUIREMENTS;
}
var i, m, j, add, packName, lang,
name = mod.name, cond, go,
adddef = ON_PAGE[name] && ON_PAGE[name].details,
d,
r, old_mod,
o, skinmod, skindef,
intl = mod.lang || mod.intl,
info = this.moduleInfo,
ftests = Y.Features && Y.Features.tests.load,
hash;
// console.log(name);
// pattern match leaves module stub that needs to be filled out
if (mod.temp && adddef) {
old_mod = mod;
mod = this.addModule(adddef, name);
mod.group = old_mod.group;
mod.pkg = old_mod.pkg;
delete mod.expanded;
}
// console.log('cache: ' + mod.langCache + ' == ' + this.lang);
// if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) {
if (mod.expanded && (!this.lang || mod.langCache === this.lang)) {
return mod.expanded;
}
d = [];
hash = {};
r = mod.requires;
o = mod.optional;
mod._parsed = true;
mod.langCache = this.lang;
for (i = 0; i < r.length; i++) {
if (!hash[r[i]]) {
d.push(r[i]);
hash[r[i]] = true;
m = this.getModule(r[i]);
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
// get the requirements from superseded modules, if any
r = mod.supersedes;
if (r) {
for (i = 0; i < r.length; i++) {
if (!hash[r[i]]) {
// if this module has submodules, the requirements list is
// expanded to include the submodules. This is so we can
// prevent dups when a submodule is already loaded and the
// parent is requested.
if (mod.submodules) {
d.push(r[i]);
}
hash[r[i]] = true;
m = this.getModule(r[i]);
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}
if (o && this.loadOptional) {
for (i = 0; i < o.length; i++) {
if (!hash[o[i]]) {
d.push(o[i]);
hash[o[i]] = true;
m = info[o[i]];
if (m) {
add = this.getRequires(m);
intl = intl || (m.expanded_map &&
(INTL in m.expanded_map));
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}
cond = this.conditions[name];
if (cond) {
if (this.testresults && ftests) {
oeach(this.testresults, function(result, id) {
var condmod = ftests[id].name;
if (!hash[condmod] && ftests[id].trigger == name) {
// console.log(id, result);
if (result && ftests[id]) {
hash[condmod] = true;
d.push(condmod);
}
}
});
} else {
oeach(cond, function(def, condmod) {
if (!hash[condmod]) {
go = def && ((def.ua && Y.UA[def.ua]) ||
(def.test && def.test(Y, r)));
if (go) {
hash[condmod] = true;
d.push(condmod);
m = this.getModule(condmod);
if (m) {
add = this.getRequires(m);
for (j = 0; j < add.length; j++) {
d.push(add[j]);
}
}
}
}
}, this);
}
}
// Create skin modules
if (mod.skinnable) {
skindef = this.skin.overrides;
if (skindef && skindef[name]) {
for (i = 0; i < skindef[name].length; i++) {
skinmod = this._addSkin(skindef[name][i], name);
d.push(skinmod);
}
} else {
skinmod = this._addSkin(this.skin.defaultSkin, name);
d.push(skinmod);
}
}
mod._parsed = false;
if (intl) {
if (mod.lang && !mod.langPack && Y.Intl) {
lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang);
packName = this.getLangPackName(lang, name);
if (packName) {
d.unshift(packName);
}
}
d.unshift(INTL);
}
mod.expanded_map = YArray.hash(d);
mod.expanded = YObject.keys(mod.expanded_map);
return mod.expanded;
},
/**
* Returns a hash of module names the supplied module satisfies.
* @method getProvides
* @param {string} name The name of the module.
* @return {object} what this module provides.
*/
getProvides: function(name) {
var m = this.getModule(name), o, s;
// supmap = this.provides;
if (!m) {
return NOT_FOUND;
}
if (m && !m.provides) {
o = {};
s = m.supersedes;
if (s) {
YArray.each(s, function(v) {
Y.mix(o, this.getProvides(v));
}, this);
}
o[name] = true;
m.provides = o;
}
return m.provides;
},
/**
* Calculates the dependency tree, the result is stored in the sorted
* property.
* @method calculate
* @param {object} o optional options object.
* @param {string} type optional argument to prune modules.
*/
calculate: function(o, type) {
if (o || type || this.dirty) {
if (o) {
this._config(o);
}
if (!this._init) {
this._setup();
}
this._explode();
if (this.allowRollup) {
this._rollup();
}
this._reduce();
this._sort();
}
},
_addLangPack: function(lang, m, packName) {
var name = m.name,
packPath,
existing = this.moduleInfo[packName];
if (!existing) {
packPath = _path((m.pkg || name), packName, JS, true);
this.addModule({ path: packPath,
intl: true,
langPack: true,
ext: m.ext,
group: m.group,
supersedes: [] }, packName, true);
if (lang) {
Y.Env.lang = Y.Env.lang || {};
Y.Env.lang[lang] = Y.Env.lang[lang] || {};
Y.Env.lang[lang][name] = true;
}
}
return this.moduleInfo[packName];
},
/**
* Investigates the current YUI configuration on the page. By default,
* modules already detected will not be loaded again unless a force
* option is encountered. Called by calculate()
* @method _setup
* @private
*/
_setup: function() {
var info = this.moduleInfo, name, i, j, m, l,
packName;
for (name in info) {
if (info.hasOwnProperty(name)) {
m = info[name];
if (m) {
// remove dups
m.requires = YObject.keys(YArray.hash(m.requires));
// Create lang pack modules
if (m.lang && m.lang.length) {
// Setup root package if the module has lang defined,
// it needs to provide a root language pack
packName = this.getLangPackName(ROOT_LANG, name);
this._addLangPack(null, m, packName);
}
}
}
}
//l = Y.merge(this.inserted);
l = {};
// available modules
if (!this.ignoreRegistered) {
Y.mix(l, GLOBAL_ENV.mods);
}
// add the ignore list to the list of loaded packages
if (this.ignore) {
Y.mix(l, YArray.hash(this.ignore));
}
// expand the list to include superseded modules
for (j in l) {
if (l.hasOwnProperty(j)) {
Y.mix(l, this.getProvides(j));
}
}
// remove modules on the force list from the loaded list
if (this.force) {
for (i = 0; i < this.force.length; i++) {
if (this.force[i] in l) {
delete l[this.force[i]];
}
}
}
Y.mix(this.loaded, l);
this._init = true;
},
/**
* Builds a module name for a language pack
* @method getLangPackName
* @param {string} lang the language code.
* @param {string} mname the module to build it for.
* @return {string} the language pack module name.
*/
getLangPackName: function(lang, mname) {
return ('lang/' + mname + ((lang) ? '_' + lang : ''));
},
/**
* Inspects the required modules list looking for additional
* dependencies. Expands the required list to include all
* required modules. Called by calculate()
* @method _explode
* @private
*/
_explode: function() {
var r = this.required, m, reqs, done = {},
self = this;
// the setup phase is over, all modules have been created
self.dirty = false;
oeach(r, function(v, name) {
if (!done[name]) {
done[name] = true;
m = self.getModule(name);
if (m) {
var expound = m.expound;
if (expound) {
r[expound] = self.getModule(expound);
reqs = self.getRequires(r[expound]);
Y.mix(r, YArray.hash(reqs));
}
reqs = self.getRequires(m);
Y.mix(r, YArray.hash(reqs));
}
}
});
},
getModule: function(mname) {
//TODO: Remove name check - it's a quick hack to fix pattern WIP
if (!mname) {
return null;
}
var p, found, pname,
m = this.moduleInfo[mname],
patterns = this.patterns;
// check the patterns library to see if we should automatically add
// the module with defaults
if (!m) {
for (pname in patterns) {
if (patterns.hasOwnProperty(pname)) {
p = patterns[pname];
// use the metadata supplied for the pattern
// as the module definition.
if (mname.indexOf(pname) > -1) {
found = p;
break;
}
}
}
if (found) {
if (p.action) {
p.action.call(this, mname, pname);
} else {
// ext true or false?
m = this.addModule(Y.merge(found), mname);
m.temp = true;
}
}
}
return m;
},
// impl in rollup submodule
_rollup: function() { },
/**
* Remove superceded modules and loaded modules. Called by
* calculate() after we have the mega list of all dependencies
* @method _reduce
* @return {object} the reduced dependency hash.
* @private
*/
_reduce: function(r) {
r = r || this.required;
var i, j, s, m, type = this.loadType;
for (i in r) {
if (r.hasOwnProperty(i)) {
m = this.getModule(i);
// remove if already loaded
if (((this.loaded[i] || ON_PAGE[i]) &&
!this.forceMap[i] && !this.ignoreRegistered) ||
(type && m && m.type != type)) {
delete r[i];
}
// remove anything this module supersedes
s = m && m.supersedes;
if (s) {
for (j = 0; j < s.length; j++) {
if (s[j] in r) {
delete r[s[j]];
}
}
}
}
}
return r;
},
_finish: function(msg, success) {
_queue.running = false;
var onEnd = this.onEnd;
if (onEnd) {
onEnd.call(this.context, {
msg: msg,
data: this.data,
success: success
});
}
this._continue();
},
_onSuccess: function() {
var self = this, skipped = Y.merge(self.skipped), fn,
failed = [], rreg = self.requireRegistration,
success, msg;
oeach(skipped, function(k) {
delete self.inserted[k];
});
self.skipped = {};
oeach(self.inserted, function(v, k) {
var mod = self.getModule(k);
if (mod && rreg && mod.type == JS && !(k in YUI.Env.mods)) {
failed.push(k);
} else {
Y.mix(self.loaded, self.getProvides(k));
}
});
fn = self.onSuccess;
msg = (failed.length) ? 'notregistered' : 'success';
success = !(failed.length);
if (fn) {
fn.call(self.context, {
msg: msg,
data: self.data,
success: success,
failed: failed,
skipped: skipped
});
}
self._finish(msg, success);
},
_onFailure: function(o) {
var f = this.onFailure, msg = 'failure: ' + o.msg;
if (f) {
f.call(this.context, {
msg: msg,
data: this.data,
success: false
});
}
this._finish(msg, false);
},
_onTimeout: function() {
var f = this.onTimeout;
if (f) {
f.call(this.context, {
msg: 'timeout',
data: this.data,
success: false
});
}
this._finish('timeout', false);
},
/**
* Sorts the dependency tree. The last step of calculate()
* @method _sort
* @private
*/
_sort: function() {
// create an indexed list
var s = YObject.keys(this.required),
// loaded = this.loaded,
done = {},
p = 0, l, a, b, j, k, moved, doneKey;
// keep going until we make a pass without moving anything
for (;;) {
l = s.length;
moved = false;
// start the loop after items that are already sorted
for (j = p; j < l; j++) {
// check the next module on the list to see if its
// dependencies have been met
a = s[j];
// check everything below current item and move if we
// find a requirement for the current item
for (k = j + 1; k < l; k++) {
doneKey = a + s[k];
if (!done[doneKey] && this._requires(a, s[k])) {
// extract the dependency so we can move it up
b = s.splice(k, 1);
// insert the dependency above the item that
// requires it
s.splice(j, 0, b[0]);
// only swap two dependencies once to short circut
// circular dependencies
done[doneKey] = true;
// keep working
moved = true;
break;
}
}
// jump out of loop if we moved something
if (moved) {
break;
// this item is sorted, move our pointer and keep going
} else {
p++;
}
}
// when we make it here and moved is false, we are
// finished sorting
if (!moved) {
break;
}
}
this.sorted = s;
},
partial: function(partial, o, type) {
this.sorted = partial;
this.insert(o, type, true);
},
_insert: function(source, o, type, skipcalc) {
// restore the state at the time of the request
if (source) {
this._config(source);
}
// build the dependency list
// don't include type so we can process CSS and script in
// one pass when the type is not specified.
if (!skipcalc) {
this.calculate(o);
}
this.loadType = type;
if (!type) {
var self = this;
this._internalCallback = function() {
var f = self.onCSS, n, p, sib;
// IE hack for style overrides that are not being applied
if (this.insertBefore && Y.UA.ie) {
n = Y.config.doc.getElementById(this.insertBefore);
p = n.parentNode;
sib = n.nextSibling;
p.removeChild(n);
if (sib) {
p.insertBefore(n, sib);
} else {
p.appendChild(n);
}
}
if (f) {
f.call(self.context, Y);
}
self._internalCallback = null;
self._insert(null, null, JS);
};
this._insert(null, null, CSS);
return;
}
// set a flag to indicate the load has started
this._loading = true;
// flag to indicate we are done with the combo service
// and any additional files will need to be loaded
// individually
this._combineComplete = {};
// start the load
this.loadNext();
},
// Once a loader operation is completely finished, process
// any additional queued items.
_continue: function() {
if (!(_queue.running) && _queue.size() > 0) {
_queue.running = true;
_queue.next()();
}
},
/**
* inserts the requested modules and their dependencies.
* <code>type</code> can be "js" or "css". Both script and
* css are inserted if type is not provided.
* @method insert
* @param {object} o optional options object.
* @param {string} type the type of dependency to insert.
*/
insert: function(o, type, skipsort) {
var self = this, copy = Y.merge(this);
delete copy.require;
delete copy.dirty;
_queue.add(function() {
self._insert(copy, o, type, skipsort);
});
this._continue();
},
/**
* Executed every time a module is loaded, and if we are in a load
* cycle, we attempt to load the next script. Public so that it
* is possible to call this if using a method other than
* Y.register to determine when scripts are fully loaded
* @method loadNext
* @param {string} mname optional the name of the module that has
* been loaded (which is usually why it is time to load the next
* one).
*/
loadNext: function(mname) {
// It is possible that this function is executed due to something
// else one the page loading a YUI module. Only react when we
// are actively loading something
if (!this._loading) {
return;
}
var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag,
comboSource, comboSources, mods, combining, urls, comboBase,
self = this,
type = self.loadType,
handleSuccess = function(o) {
self.loadNext(o.data);
},
handleCombo = function(o) {
self._combineComplete[type] = true;
var i, len = combining.length;
for (i = 0; i < len; i++) {
self.inserted[combining[i]] = true;
}
handleSuccess(o);
};
if (self.combine && (!self._combineComplete[type])) {
combining = [];
self._combining = combining;
s = self.sorted;
len = s.length;
// the default combo base
comboBase = self.comboBase;
url = comboBase;
urls = [];
comboSources = {};
for (i = 0; i < len; i++) {
comboSource = comboBase;
m = self.getModule(s[i]);
groupName = m && m.group;
if (groupName) {
group = self.groups[groupName];
if (!group.combine) {
m.combine = false;
continue;
}
m.combine = true;
if (group.comboBase) {
comboSource = group.comboBase;
}
if (group.root) {
m.root = group.root;
}
}
comboSources[comboSource] = comboSources[comboSource] || [];
comboSources[comboSource].push(m);
}
for (j in comboSources) {
if (comboSources.hasOwnProperty(j)) {
url = j;
mods = comboSources[j];
len = mods.length;
for (i = 0; i < len; i++) {
// m = self.getModule(s[i]);
m = mods[i];
// Do not try to combine non-yui JS unless combo def
// is found
if (m && (m.type === type) && (m.combine || !m.ext)) {
frag = (m.root || self.root) + m.path;
if ((url !== j) && (i < (len - 1)) &&
((frag.length + url.length) > self.maxURLLength)) {
urls.push(self._filter(url));
url = j;
}
url += frag;
if (i < (len - 1)) {
url += '&';
}
combining.push(m.name);
}
}
if (combining.length && (url != j)) {
urls.push(self._filter(url));
}
}
}
if (combining.length) {
// if (m.type === CSS) {
if (type === CSS) {
fn = Y.Get.css;
attr = self.cssAttributes;
} else {
fn = Y.Get.script;
attr = self.jsAttributes;
}
fn(urls, {
data: self._loading,
onSuccess: handleCombo,
onFailure: self._onFailure,
onTimeout: self._onTimeout,
insertBefore: self.insertBefore,
charset: self.charset,
attributes: attr,
timeout: self.timeout,
autopurge: false,
context: self
});
return;
} else {
self._combineComplete[type] = true;
}
}
if (mname) {
// if the module that was just loaded isn't what we were expecting,
// continue to wait
if (mname !== self._loading) {
return;
}
// The global handler that is called when each module is loaded
// will pass that module name to this function. Storing this
// data to avoid loading the same module multiple times
// centralize this in the callback
self.inserted[mname] = true;
// self.loaded[mname] = true;
// provided = self.getProvides(mname);
// Y.mix(self.loaded, provided);
// Y.mix(self.inserted, provided);
if (self.onProgress) {
self.onProgress.call(self.context, {
name: mname,
data: self.data
});
}
}
s = self.sorted;
len = s.length;
for (i = 0; i < len; i = i + 1) {
// this.inserted keeps track of what the loader has loaded.
// move on if this item is done.
if (s[i] in self.inserted) {
continue;
}
// Because rollups will cause multiple load notifications
// from Y, loadNext may be called multiple times for
// the same module when loading a rollup. We can safely
// skip the subsequent requests
if (s[i] === self._loading) {
return;
}
// log("inserting " + s[i]);
m = self.getModule(s[i]);
if (!m) {
if (!self.skipped[s[i]]) {
msg = 'Undefined module ' + s[i] + ' skipped';
// self.inserted[s[i]] = true;
self.skipped[s[i]] = true;
}
continue;
}
group = (m.group && self.groups[m.group]) || NOT_FOUND;
// The load type is stored to offer the possibility to load
// the css separately from the script.
if (!type || type === m.type) {
self._loading = s[i];
if (m.type === CSS) {
fn = Y.Get.css;
attr = self.cssAttributes;
} else {
fn = Y.Get.script;
attr = self.jsAttributes;
}
url = (m.fullpath) ? self._filter(m.fullpath, s[i]) :
self._url(m.path, s[i], group.base || m.base);
fn(url, {
data: s[i],
onSuccess: handleSuccess,
insertBefore: self.insertBefore,
charset: self.charset,
attributes: attr,
onFailure: self._onFailure,
onTimeout: self._onTimeout,
timeout: self.timeout,
autopurge: false,
context: self
});
return;
}
}
// we are finished
self._loading = null;
fn = self._internalCallback;
// internal callback for loading css first
if (fn) {
self._internalCallback = null;
fn.call(self);
} else {
self._onSuccess();
}
},
/**
* Apply filter defined for this instance to a url/path
* method _filter
* @param {string} u the string to filter.
* @param {string} name the name of the module, if we are processing
* a single module as opposed to a combined url.
* @return {string} the filtered string.
* @private
*/
_filter: function(u, name) {
var f = this.filter,
hasFilter = name && (name in this.filters),
modFilter = hasFilter && this.filters[name];
if (u) {
if (hasFilter) {
f = (L.isString(modFilter)) ?
this.FILTER_DEFS[modFilter.toUpperCase()] || null :
modFilter;
}
if (f) {
u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr);
}
}
return u;
},
/**
* Generates the full url for a module
* method _url
* @param {string} path the path fragment.
* @return {string} the full url.
* @private
*/
_url: function(path, name, base) {
return this._filter((base || this.base || '') + path, name);
}
};
}, '@VERSION@' ,{requires:['get']});
YUI.add('loader-rollup', function(Y) {
/**
* Optional automatic rollup logic for reducing http connections
* when not using a combo service.
* @module loader
* @submodule rollup
*/
/**
* Look for rollup packages to determine if all of the modules a
* rollup supersedes are required. If so, include the rollup to
* help reduce the total number of connections required. Called
* by calculate(). This is an optional feature, and requires the
* appropriate submodule to function.
* @method _rollup
* @for Loader
* @private
*/
Y.Loader.prototype._rollup = function() {
var i, j, m, s, r = this.required, roll,
info = this.moduleInfo, rolled, c, smod;
// find and cache rollup modules
if (this.dirty || !this.rollups) {
this.rollups = {};
for (i in info) {
if (info.hasOwnProperty(i)) {
m = this.getModule(i);
// if (m && m.rollup && m.supersedes) {
if (m && m.rollup) {
this.rollups[i] = m;
}
}
}
this.forceMap = (this.force) ? Y.Array.hash(this.force) : {};
}
// make as many passes as needed to pick up rollup rollups
for (;;) {
rolled = false;
// go through the rollup candidates
for (i in this.rollups) {
if (this.rollups.hasOwnProperty(i)) {
// there can be only one, unless forced
if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) {
m = this.getModule(i);
s = m.supersedes || [];
roll = false;
// @TODO remove continue
if (!m.rollup) {
continue;
}
c = 0;
// check the threshold
for (j = 0; j < s.length; j++) {
smod = info[s[j]];
// if the superseded module is loaded, we can't
// load the rollup unless it has been forced.
if (this.loaded[s[j]] && !this.forceMap[s[j]]) {
roll = false;
break;
// increment the counter if this module is required.
// if we are beyond the rollup threshold, we will
// use the rollup module
} else if (r[s[j]] && m.type == smod.type) {
c++;
roll = (c >= m.rollup);
if (roll) {
break;
}
}
}
if (roll) {
// add the rollup
r[i] = true;
rolled = true;
// expand the rollup's dependencies
this.getRequires(m);
}
}
}
}
// if we made it here w/o rolling up something, we are done
if (!rolled) {
break;
}
}
};
}, '@VERSION@' ,{requires:['loader-base']});
YUI.add('loader-yui3', function(Y) {
/* This file is auto-generated by src/loader/meta_join.py */
/**
* YUI 3 module metadata
* @module loader
* @submodule yui3
*/
YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || {
"anim": {
"submodules": {
"anim-base": {
"requires": [
"base-base",
"node-style"
]
},
"anim-color": {
"requires": [
"anim-base"
]
},
"anim-curve": {
"requires": [
"anim-xy"
]
},
"anim-easing": {
"requires": [
"anim-base"
]
},
"anim-node-plugin": {
"requires": [
"node-pluginhost",
"anim-base"
]
},
"anim-scroll": {
"requires": [
"anim-base"
]
},
"anim-xy": {
"requires": [
"anim-base",
"node-screen"
]
}
}
},
"app": {
"submodules": {
"controller": {
"requires": [
"base-build"
]
},
"model": {
"optional": [
"json-parse"
],
"requires": [
"base-build",
"escape"
]
},
"model-list": {
"requires": [
"array-extras",
"array-invoke",
"arraylist",
"base-build",
"model"
]
},
"view": {
"requires": [
"base-build",
"node-event-delegate"
]
}
}
},
"arraysort": {
"requires": [
"yui-base"
]
},
"async-queue": {
"requires": [
"event-custom"
]
},
"attribute": {
"submodules": {
"attribute-base": {
"requires": [
"event-custom"
]
},
"attribute-complex": {
"requires": [
"attribute-base"
]
}
}
},
"autocomplete": {
"submodules": {
"autocomplete-base": {
"optional": [
"autocomplete-sources"
],
"plugins": {
"autocomplete-filters": {
"path": "autocomplete/autocomplete-filters-min.js",
"requires": [
"array-extras",
"text-wordbreak"
]
},
"autocomplete-filters-accentfold": {
"path": "autocomplete/autocomplete-filters-accentfold-min.js",
"requires": [
"array-extras",
"text-accentfold",
"text-wordbreak"
]
},
"autocomplete-highlighters": {
"path": "autocomplete/autocomplete-highlighters-min.js",
"requires": [
"array-extras",
"highlight-base"
]
},
"autocomplete-highlighters-accentfold": {
"path": "autocomplete/autocomplete-highlighters-accentfold-min.js",
"requires": [
"array-extras",
"highlight-accentfold"
]
}
},
"requires": [
"array-extras",
"base-build",
"escape",
"event-valuechange",
"node-base"
]
},
"autocomplete-list": {
"after": "autocomplete-sources",
"lang": [
"en"
],
"plugins": {
"autocomplete-list-keys": {
"condition": {
"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"
},
"path": "autocomplete/autocomplete-list-keys-min.js",
"requires": [
"autocomplete-list",
"base-build"
]
},
"autocomplete-plugin": {
"path": "autocomplete/autocomplete-plugin-min.js",
"requires": [
"autocomplete-list",
"node-pluginhost"
]
}
},
"requires": [
"autocomplete-base",
"event-resize",
"selector-css3",
"shim-plugin",
"widget",
"widget-position",
"widget-position-align"
],
"skinnable": true
},
"autocomplete-sources": {
"optional": [
"io-base",
"json-parse",
"jsonp",
"yql"
],
"requires": [
"autocomplete-base"
]
}
}
},
"base": {
"submodules": {
"base-base": {
"after": [
"attribute-complex"
],
"requires": [
"attribute-base"
]
},
"base-build": {
"requires": [
"base-base"
]
},
"base-pluginhost": {
"requires": [
"base-base",
"pluginhost"
]
}
}
},
"cache": {
"submodules": {
"cache-base": {
"requires": [
"base"
]
},
"cache-offline": {
"requires": [
"cache-base",
"json"
]
},
"cache-plugin": {
"requires": [
"plugin",
"cache-base"
]
}
}
},
"charts": {
"requires": [
"dom",
"datatype",
"event-custom",
"event-mouseenter",
"widget",
"widget-position",
"widget-stack"
]
},
"classnamemanager": {
"requires": [
"yui-base"
]
},
"collection": {
"submodules": {
"array-extras": {},
"array-invoke": {},
"arraylist": {},
"arraylist-add": {
"requires": [
"arraylist"
]
},
"arraylist-filter": {
"requires": [
"arraylist"
]
}
}
},
"compat": {
"requires": [
"event-base",
"dom",
"dump",
"substitute"
]
},
"console": {
"lang": [
"en",
"es"
],
"plugins": {
"console-filters": {
"requires": [
"plugin",
"console"
],
"skinnable": true
}
},
"requires": [
"yui-log",
"widget",
"substitute"
],
"skinnable": true
},
"cookie": {
"requires": [
"yui-base"
]
},
"cssbase": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"path": "cssbase/base-min.css",
"type": "css"
},
"cssbase-context": {
"after": [
"cssreset",
"cssfonts",
"cssgrids",
"cssreset-context",
"cssfonts-context",
"cssgrids-context"
],
"path": "cssbase/base-context-min.css",
"type": "css"
},
"cssfonts": {
"path": "cssfonts/fonts-min.css",
"type": "css"
},
"cssfonts-context": {
"path": "cssfonts/fonts-context-min.css",
"type": "css"
},
"cssgrids": {
"optional": [
"cssreset",
"cssfonts"
],
"path": "cssgrids/grids-min.css",
"type": "css"
},
"cssgrids-context-deprecated": {
"optional": [
"cssreset-context"
],
"path": "cssgrids-deprecated/grids-context-min.css",
"requires": [
"cssfonts-context"
],
"type": "css"
},
"cssgrids-deprecated": {
"optional": [
"cssreset"
],
"path": "cssgrids-deprecated/grids-min.css",
"requires": [
"cssfonts"
],
"type": "css"
},
"cssreset": {
"path": "cssreset/reset-min.css",
"type": "css"
},
"cssreset-context": {
"path": "cssreset/reset-context-min.css",
"type": "css"
},
"dataschema": {
"submodules": {
"dataschema-array": {
"requires": [
"dataschema-base"
]
},
"dataschema-base": {
"requires": [
"base"
]
},
"dataschema-json": {
"requires": [
"dataschema-base",
"json"
]
},
"dataschema-text": {
"requires": [
"dataschema-base"
]
},
"dataschema-xml": {
"requires": [
"dataschema-base"
]
}
}
},
"datasource": {
"submodules": {
"datasource-arrayschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-array"
]
},
"datasource-cache": {
"requires": [
"datasource-local",
"plugin",
"cache-base"
]
},
"datasource-function": {
"requires": [
"datasource-local"
]
},
"datasource-get": {
"requires": [
"datasource-local",
"get"
]
},
"datasource-io": {
"requires": [
"datasource-local",
"io-base"
]
},
"datasource-jsonschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-json"
]
},
"datasource-local": {
"requires": [
"base"
]
},
"datasource-polling": {
"requires": [
"datasource-local"
]
},
"datasource-textschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-text"
]
},
"datasource-xmlschema": {
"requires": [
"datasource-local",
"plugin",
"dataschema-xml"
]
}
}
},
"datatable": {
"submodules": {
"datatable-base": {
"requires": [
"recordset-base",
"widget",
"substitute",
"event-mouseenter"
],
"skinnable": true
},
"datatable-datasource": {
"requires": [
"datatable-base",
"plugin",
"datasource-local"
]
},
"datatable-scroll": {
"requires": [
"datatable-base",
"plugin",
"stylesheet"
]
},
"datatable-sort": {
"lang": [
"en"
],
"requires": [
"datatable-base",
"plugin",
"recordset-sort"
]
}
}
},
"datatype": {
"submodules": {
"datatype-date": {
"lang": [
"ar",
"ar-JO",
"ca",
"ca-ES",
"da",
"da-DK",
"de",
"de-AT",
"de-DE",
"el",
"el-GR",
"en",
"en-AU",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JO",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-US",
"es",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-EC",
"es-ES",
"es-MX",
"es-PE",
"es-PY",
"es-US",
"es-UY",
"es-VE",
"fi",
"fi-FI",
"fr",
"fr-BE",
"fr-CA",
"fr-FR",
"hi",
"hi-IN",
"id",
"id-ID",
"it",
"it-IT",
"ja",
"ja-JP",
"ko",
"ko-KR",
"ms",
"ms-MY",
"nb",
"nb-NO",
"nl",
"nl-BE",
"nl-NL",
"pl",
"pl-PL",
"pt",
"pt-BR",
"ro",
"ro-RO",
"ru",
"ru-RU",
"sv",
"sv-SE",
"th",
"th-TH",
"tr",
"tr-TR",
"vi",
"vi-VN",
"zh-Hans",
"zh-Hans-CN",
"zh-Hant",
"zh-Hant-HK",
"zh-Hant-TW"
],
"requires": [
"yui-base"
],
"supersedes": [
"datatype-date-format"
]
},
"datatype-number": {
"requires": [
"yui-base"
]
},
"datatype-xml": {
"requires": [
"yui-base"
]
}
}
},
"datatype-date-format": {
"path": "datatype/datatype-date-format-min.js"
},
"dd": {
"plugins": {
"dd-drop-plugin": {
"requires": [
"dd-drop"
]
},
"dd-gestures": {
"condition": {
"name": "dd-gestures",
"test": function(Y) {
return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome));
},
"trigger": "dd-drag"
},
"requires": [
"dd-drag",
"event-move"
]
},
"dd-plugin": {
"optional": [
"dd-constrain",
"dd-proxy"
],
"requires": [
"dd-drag"
]
}
},
"submodules": {
"dd-constrain": {
"requires": [
"dd-drag"
]
},
"dd-ddm": {
"requires": [
"dd-ddm-base",
"event-resize"
]
},
"dd-ddm-base": {
"requires": [
"node",
"base",
"yui-throttle",
"classnamemanager"
]
},
"dd-ddm-drop": {
"requires": [
"dd-ddm"
]
},
"dd-delegate": {
"requires": [
"dd-drag",
"dd-drop-plugin",
"event-mouseenter"
]
},
"dd-drag": {
"requires": [
"dd-ddm-base"
]
},
"dd-drop": {
"requires": [
"dd-ddm-drop"
]
},
"dd-proxy": {
"requires": [
"dd-drag"
]
},
"dd-scroll": {
"requires": [
"dd-drag"
]
}
}
},
"dial": {
"lang": [
"en",
"es"
],
"requires": [
"widget",
"dd-drag",
"substitute",
"event-mouseenter",
"event-move",
"transition",
"intl"
],
"skinnable": true
},
"dom": {
"plugins": {
"dom-deprecated": {
"requires": [
"dom-base"
]
},
"dom-style-ie": {
"condition": {
"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"
},
"requires": [
"dom-style"
]
},
"selector-css2": {
"condition": {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
},
"requires": [
"selector-native"
]
},
"selector-css3": {
"requires": [
"selector-native",
"selector-css2"
]
}
},
"requires": [
"oop"
],
"submodules": {
"dom-attrs": {
"requires": [
"dom-core"
]
},
"dom-base": {
"requires": [
"dom-core",
"dom-attrs",
"dom-create",
"dom-class",
"dom-size"
]
},
"dom-class": {
"requires": [
"dom-core"
]
},
"dom-core": {
"requires": [
"oop",
"features"
]
},
"dom-create": {
"requires": [
"dom-core"
]
},
"dom-screen": {
"requires": [
"dom-core",
"dom-style"
]
},
"dom-size": {
"requires": [
"dom-base"
]
},
"dom-style": {
"requires": [
"dom-core"
]
},
"selector": {
"requires": [
"selector-native"
]
},
"selector-native": {
"requires": [
"dom-core"
]
}
}
},
"dump": {
"requires": [
"yui-base"
]
},
"editor": {
"submodules": {
"createlink-base": {
"requires": [
"editor-base"
]
},
"editor-base": {
"requires": [
"base",
"frame",
"node",
"exec-command",
"selection"
]
},
"editor-bidi": {
"requires": [
"editor-base"
]
},
"editor-br": {
"requires": [
"node"
]
},
"editor-lists": {
"requires": [
"editor-base"
]
},
"editor-para": {
"requires": [
"node"
]
},
"exec-command": {
"requires": [
"frame"
]
},
"frame": {
"requires": [
"base",
"node",
"selector-css3",
"substitute"
]
},
"selection": {
"requires": [
"node"
]
}
}
},
"escape": {},
"event": {
"after": "node-base",
"plugins": {
"event-base-ie": {
"after": [
"event-base"
],
"condition": {
"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"
},
"requires": [
"node-base"
]
},
"event-touch": {
"requires": [
"node-base"
]
}
},
"submodules": {
"event-base": {
"after": "node-base",
"requires": [
"event-custom-base"
]
},
"event-delegate": {
"requires": [
"node-base"
]
},
"event-focus": {
"requires": [
"event-synthetic"
]
},
"event-hover": {
"requires": [
"event-mouseenter"
]
},
"event-key": {
"requires": [
"event-synthetic"
]
},
"event-mouseenter": {
"requires": [
"event-synthetic"
]
},
"event-mousewheel": {
"requires": [
"event-synthetic"
]
},
"event-resize": {
"requires": [
"event-synthetic"
]
},
"event-synthetic": {
"requires": [
"node-base",
"event-custom-complex"
]
}
}
},
"event-custom": {
"submodules": {
"event-custom-base": {
"requires": [
"oop"
]
},
"event-custom-complex": {
"requires": [
"event-custom-base"
]
}
}
},
"event-gestures": {
"submodules": {
"event-flick": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
},
"event-move": {
"requires": [
"node-base",
"event-touch",
"event-synthetic"
]
}
}
},
"event-simulate": {
"requires": [
"event-base"
]
},
"event-valuechange": {
"requires": [
"event-focus",
"event-synthetic"
]
},
"highlight": {
"submodules": {
"highlight-accentfold": {
"requires": [
"highlight-base",
"text-accentfold"
]
},
"highlight-base": {
"requires": [
"array-extras",
"escape",
"text-wordbreak"
]
}
}
},
"history": {
"plugins": {
"history-hash-ie": {
"condition": {
"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"
},
"requires": [
"history-hash",
"node-base"
]
}
},
"submodules": {
"history-base": {
"after": [
"history-deprecated"
],
"requires": [
"event-custom-complex"
]
},
"history-hash": {
"after": [
"history-html5"
],
"requires": [
"event-synthetic",
"history-base",
"yui-later"
]
},
"history-html5": {
"optional": [
"json"
],
"requires": [
"event-base",
"history-base",
"node-base"
]
}
}
},
"history-deprecated": {
"requires": [
"node"
]
},
"imageloader": {
"requires": [
"base-base",
"node-style",
"node-screen"
]
},
"intl": {
"requires": [
"intl-base",
"event-custom"
]
},
"io": {
"submodules": {
"io-base": {
"requires": [
"event-custom-base",
"querystring-stringify-simple"
]
},
"io-form": {
"requires": [
"io-base",
"node-base",
"node-style"
]
},
"io-queue": {
"requires": [
"io-base",
"queue-promote"
]
},
"io-upload-iframe": {
"requires": [
"io-base",
"node-base"
]
},
"io-xdr": {
"requires": [
"io-base",
"datatype-xml"
]
}
}
},
"json": {
"submodules": {
"json-parse": {
"requires": [
"yui-base"
]
},
"json-stringify": {
"requires": [
"yui-base"
]
}
}
},
"jsonp": {
"plugins": {
"jsonp-url": {
"requires": [
"jsonp"
]
}
},
"requires": [
"get",
"oop"
]
},
"loader": {
"submodules": {
"loader-base": {
"requires": [
"get"
]
},
"loader-rollup": {
"requires": [
"loader-base"
]
},
"loader-yui3": {
"requires": [
"loader-base"
]
}
}
},
"node": {
"plugins": {
"align-plugin": {
"requires": [
"node-screen",
"node-pluginhost"
]
},
"node-deprecated": {
"requires": [
"node-base"
]
},
"node-event-simulate": {
"requires": [
"node-base",
"event-simulate"
]
},
"node-load": {
"requires": [
"node-base",
"io-base"
]
},
"shim-plugin": {
"requires": [
"node-style",
"node-pluginhost"
]
}
},
"submodules": {
"node-base": {
"requires": [
"dom-base",
"selector-css2",
"event-base"
]
},
"node-event-delegate": {
"requires": [
"node-base",
"event-delegate"
]
},
"node-pluginhost": {
"requires": [
"node-base",
"pluginhost"
]
},
"node-screen": {
"requires": [
"dom-screen",
"node-base"
]
},
"node-style": {
"requires": [
"dom-style",
"node-base"
]
}
}
},
"node-flick": {
"requires": [
"classnamemanager",
"transition",
"event-flick",
"plugin"
],
"skinnable": true
},
"node-focusmanager": {
"requires": [
"attribute",
"node",
"plugin",
"node-event-simulate",
"event-key",
"event-focus"
]
},
"node-menunav": {
"requires": [
"node",
"classnamemanager",
"plugin",
"node-focusmanager"
],
"skinnable": true
},
"oop": {
"requires": [
"yui-base"
]
},
"overlay": {
"requires": [
"widget",
"widget-stdmod",
"widget-position",
"widget-position-align",
"widget-stack",
"widget-position-constrain"
],
"skinnable": true
},
"plugin": {
"requires": [
"base-base"
]
},
"pluginhost": {
"submodules": {
"pluginhost-base": {
"requires": [
"yui-base"
]
},
"pluginhost-config": {
"requires": [
"pluginhost-base"
]
}
}
},
"profiler": {
"requires": [
"yui-base"
]
},
"querystring": {
"submodules": {
"querystring-parse": {
"requires": [
"yui-base",
"array-extras"
]
},
"querystring-stringify": {
"requires": [
"yui-base"
]
}
}
},
"querystring-parse-simple": {
"path": "querystring/querystring-parse-simple-min.js",
"requires": [
"yui-base"
]
},
"querystring-stringify-simple": {
"path": "querystring/querystring-stringify-simple-min.js",
"requires": [
"yui-base"
]
},
"queue-promote": {
"requires": [
"yui-base"
]
},
"queue-run": {
"path": "async-queue/async-queue-min.js",
"requires": [
"event-custom"
]
},
"recordset": {
"submodules": {
"recordset-base": {
"requires": [
"base",
"arraylist"
]
},
"recordset-filter": {
"requires": [
"recordset-base",
"array-extras",
"plugin"
]
},
"recordset-indexer": {
"requires": [
"recordset-base",
"plugin"
]
},
"recordset-sort": {
"requires": [
"arraysort",
"recordset-base",
"plugin"
]
}
}
},
"resize": {
"plugins": {
"resize-plugin": {
"optional": [
"resize-constrain"
],
"requires": [
"resize-base",
"plugin"
]
}
},
"submodules": {
"resize-base": {
"requires": [
"widget",
"substitute",
"event",
"oop",
"dd-drag",
"dd-delegate",
"dd-drop"
],
"skinnable": true
},
"resize-constrain": {
"requires": [
"plugin",
"resize-base"
]
},
"resize-proxy": {
"requires": [
"plugin",
"resize-base"
]
}
}
},
"scrollview": {
"plugins": {
"scrollview-base": {
"path": "scrollview/scrollview-base-min.js",
"requires": [
"widget",
"event-gestures",
"transition"
],
"skinnable": true
},
"scrollview-base-ie": {
"condition": {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
},
"requires": [
"scrollview-base"
]
},
"scrollview-paginator": {
"path": "scrollview/scrollview-paginator-min.js",
"requires": [
"plugin"
]
},
"scrollview-scrollbars": {
"path": "scrollview/scrollview-scrollbars-min.js",
"requires": [
"plugin"
],
"skinnable": true
}
},
"requires": [
"scrollview-base",
"scrollview-scrollbars"
]
},
"slider": {
"submodules": {
"clickable-rail": {
"requires": [
"slider-base"
]
},
"range-slider": {
"requires": [
"slider-base",
"slider-value-range",
"clickable-rail"
]
},
"slider-base": {
"requires": [
"widget",
"dd-constrain",
"substitute"
],
"skinnable": true
},
"slider-value-range": {
"requires": [
"slider-base"
]
}
}
},
"sortable": {
"plugins": {
"sortable-scroll": {
"requires": [
"dd-scroll"
]
}
},
"requires": [
"dd-delegate",
"dd-drop-plugin",
"dd-proxy"
]
},
"stylesheet": {
"requires": [
"yui-base"
]
},
"substitute": {
"optional": [
"dump"
]
},
"swf": {
"requires": [
"event-custom",
"node",
"swfdetect"
]
},
"swfdetect": {},
"tabview": {
"plugins": {
"tabview-base": {
"requires": [
"node-event-delegate",
"classnamemanager",
"skin-sam-tabview"
]
},
"tabview-plugin": {
"requires": [
"tabview-base"
]
}
},
"requires": [
"widget",
"widget-parent",
"widget-child",
"tabview-base",
"node-pluginhost",
"node-focusmanager"
],
"skinnable": true
},
"test": {
"requires": [
"substitute",
"node",
"json",
"event-simulate"
],
"skinnable": true
},
"text": {
"submodules": {
"text-accentfold": {
"requires": [
"array-extras",
"text-data-accentfold"
]
},
"text-data-accentfold": {},
"text-data-wordbreak": {},
"text-wordbreak": {
"requires": [
"array-extras",
"text-data-wordbreak"
]
}
}
},
"transition": {
"submodules": {
"transition-native": {
"requires": [
"node-base"
]
},
"transition-timer": {
"requires": [
"transition-native",
"node-style"
]
}
}
},
"uploader": {
"requires": [
"event-custom",
"node",
"base",
"swf"
]
},
"widget": {
"plugins": {
"widget-base-ie": {
"condition": {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
},
"requires": [
"widget-base"
]
},
"widget-child": {
"requires": [
"base-build",
"widget"
]
},
"widget-parent": {
"requires": [
"base-build",
"arraylist",
"widget"
]
},
"widget-position": {
"requires": [
"base-build",
"node-screen",
"widget"
]
},
"widget-position-align": {
"requires": [
"widget-position"
]
},
"widget-position-constrain": {
"requires": [
"widget-position"
]
},
"widget-stack": {
"requires": [
"base-build",
"widget"
],
"skinnable": true
},
"widget-stdmod": {
"requires": [
"base-build",
"widget"
]
}
},
"skinnable": true,
"submodules": {
"widget-base": {
"requires": [
"attribute",
"event-focus",
"base-base",
"base-pluginhost",
"node-base",
"node-style",
"classnamemanager"
]
},
"widget-htmlparser": {
"requires": [
"widget-base"
]
},
"widget-skin": {
"requires": [
"widget-base"
]
},
"widget-uievents": {
"requires": [
"widget-base",
"node-event-delegate"
]
}
}
},
"widget-anim": {
"requires": [
"plugin",
"anim-base",
"widget"
]
},
"widget-locale": {
"path": "widget/widget-locale-min.js",
"requires": [
"widget-base"
]
},
"yql": {
"requires": [
"jsonp",
"jsonp-url"
]
},
"yui": {
"submodules": {
"features": {
"requires": [
"yui-base"
]
},
"get": {
"requires": [
"yui-base"
]
},
"intl-base": {
"requires": [
"yui-base"
]
},
"rls": {
"requires": [
"get",
"features"
]
},
"yui-base": {},
"yui-later": {
"requires": [
"yui-base"
]
},
"yui-log": {
"requires": [
"yui-base"
]
},
"yui-throttle": {
"requires": [
"yui-base"
]
}
}
}
};
YUI.Env[Y.version].md5 = '5c6f60dc2a580d07a649f28d41367ff0';
}, '@VERSION@' ,{requires:['loader-base']});
YUI.add('loader', function(Y){}, '@VERSION@' ,{use:['loader-base', 'loader-rollup', 'loader-yui3' ]});
|
src/routes/index.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { UserAuthWrapper } from 'redux-auth-wrapper'
import store from '../store';
import { syncHistoryWithStore, routerActions } from 'react-router-redux';
import AppContainer from '../containers/AppContainer';
import SchoolUserPage from '../components/layouts/SchoolUserPage';
import AdminPage from '../components/layouts/AdminPage';
import CallbackPage from '../components/callback';
import PublicPage from '../components/layouts/PublicPage';
const history = syncHistoryWithStore(browserHistory, store);
const UserIsAuthenticated = UserAuthWrapper({
authSelector: state => state.oidc.user, // how to get the user state
redirectAction: routerActions.replace, // the redux action to dispatch for redirect
wrapperDisplayName: 'UserIsAuthenticated' // a nice name for this auth check
})
const AdminIsAuthenticated = UserAuthWrapper({
authSelector: state => state.oidc.user, // how to get the user state
redirectAction: routerActions.replace, // the redux action to dispatch for redirect
wrapperDisplayName: 'UserIsAuthenticated' // a nice name for this auth check
})
export default function Routes(props) {
return (
<Router history={history}>
<Route path="/" component={AppContainer}>
<IndexRoute component={PublicPage}/>
<Route path="/callback" component={CallbackPage} />
<Route path="/user" component={SchoolUserPage} />
<Route path="/admin" component={AdminPage} />
</Route>
</Router>
);
}
|
src/TableBody.js | prajapati-parth/react-bootstrap-table | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Utils from './util';
import Const from './Const';
import TableRow from './TableRow';
import TableColumn from './TableColumn';
import TableEditColumn from './TableEditColumn';
import classSet from 'classnames';
import ExpandComponent from './ExpandComponent';
class TableBody extends Component {
constructor(props) {
super(props);
this.state = {
currEditCell: null
};
}
render() {
const { cellEdit, beforeShowError, x, y, keyBoardNav, trStyle, version } = this.props;
const tableClasses = classSet('table', {
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-hover': this.props.hover,
'table-condensed': this.props.condensed
}, this.props.tableBodyClass);
const noneditableRows = (cellEdit.nonEditableRows && cellEdit.nonEditableRows()) || [];
const unselectable = this.props.selectRow.unselectable || [];
const isSelectRowDefined = this._isSelectRowDefined();
const tableHeader = Utils.renderColGroup(this.props.columns,
this.props.selectRow, this.props.expandColumnOptions, version);
const inputType = this.props.selectRow.mode === Const.ROW_SELECT_SINGLE ? 'radio' : 'checkbox';
const CustomComponent = this.props.selectRow.customComponent;
const enableKeyBoardNav = (keyBoardNav === true || typeof keyBoardNav === 'object');
const customEditAndNavStyle = typeof keyBoardNav === 'object' ?
keyBoardNav.customStyleOnEditCell :
null;
const customNavStyle = typeof keyBoardNav === 'object' ?
keyBoardNav.customStyle :
null;
const ExpandColumnCustomComponent = this.props.expandColumnOptions.expandColumnComponent;
let expandColSpan = this.props.columns.filter(col => col && !col.hidden).length;
if (isSelectRowDefined && !this.props.selectRow.hideSelectColumn) {
expandColSpan += 1;
}
let tabIndex = 1;
if (this.props.expandColumnOptions.expandColumnVisible) {
expandColSpan += 1;
}
let tableRows = this.props.data.map(function(data, r) {
const tableColumns = this.props.columns.filter(_ => _ != null).map(function(column, i) {
const fieldValue = data[column.name];
const isFocusCell = r === y && i === x;
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
column.editable.readOnly !== true &&
this.state.currEditCell !== null &&
this.state.currEditCell.rid === r &&
this.state.currEditCell.cid === i &&
noneditableRows.indexOf(data[this.props.keyField]) === -1) {
let editable = column.editable;
const format = column.format ? function(value) {
return column.format(value, data, column.formatExtraData, r).replace(/<.*?>/g, '');
} : false;
if (Utils.isFunction(column.editable)) {
editable = column.editable(fieldValue, data, r, i);
}
return (
<TableEditColumn
completeEdit={ this.handleCompleteEditCell }
// add by bluespring for column editor customize
editable={ editable }
attrs={ column.editAttrs }
customEditor={ column.customEditor }
format={ column.format ? format : false }
key={ i }
blurToSave={ cellEdit.blurToSave }
blurToEscape={ cellEdit.blurToEscape }
onTab={ this.handleEditCell }
rowIndex={ r }
colIndex={ i }
row={ data }
fieldValue={ fieldValue }
className={ column.editClassName }
invalidColumnClassName={ column.invalidEditColumnClassName }
beforeShowError={ beforeShowError }
isFocus={ isFocusCell }
customStyleWithNav={ customEditAndNavStyle } />
);
} else {
// add by bluespring for className customize
let formattedValue;
let columnChild = fieldValue && fieldValue.toString();
let columnTitle = null;
let tdClassName = column.className;
if (Utils.isFunction(column.className)) {
tdClassName = column.className(fieldValue, data, r, i);
}
if (typeof column.format !== 'undefined') {
formattedValue = column.format(fieldValue, data, column.formatExtraData, r);
if (!React.isValidElement(formattedValue)) {
columnChild = (
<div dangerouslySetInnerHTML={ { __html: formattedValue } }></div>
);
} else {
columnChild = formattedValue;
}
}
if (Utils.isFunction(column.columnTitle)) {
columnTitle = column.columnTitle(fieldValue, data, r, i);
} else if (typeof column.columnTitle === 'string') {
columnTitle = column.columnTitle;
} else if (column.columnTitle) {
if (formattedValue) columnTitle = formattedValue.toString();
else if (fieldValue) columnTitle = fieldValue.toString();
}
return (
<TableColumn key={ i }
rIndex={ r }
dataAlign={ column.align }
className={ tdClassName }
columnTitle={ columnTitle }
cellEdit={ cellEdit }
hidden={ column.hidden }
onEdit={ this.handleEditCell }
width={ column.width }
onClick={ this.handleClickCell }
attrs={ column.attrs }
style={ column.style }
tabIndex={ (tabIndex++) + '' }
isFocus={ isFocusCell }
keyBoardNav={ enableKeyBoardNav }
onKeyDown={ this.handleCellKeyDown }
customNavStyle={ customNavStyle }
row={ data }
withoutTabIndex={ this.props.withoutTabIndex }>
{ columnChild }
</TableColumn>
);
}
}, this);
const key = data[this.props.keyField];
const disable = unselectable.indexOf(key) !== -1;
const selected = this.props.selectedRowKeys.indexOf(key) !== -1;
const selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ?
this.renderSelectRowColumn(selected, inputType, disable, CustomComponent, r, data) : null;
const expandedRowColumn = this.renderExpandRowColumn(
this.props.expandableRow && this.props.expandableRow(data),
this.props.expanding.indexOf(key) > -1,
ExpandColumnCustomComponent, r
);
const haveExpandContent = this.props.expandableRow && this.props.expandableRow(data);
const isExpanding = haveExpandContent && this.props.expanding.indexOf(key) > -1;
// add by bluespring for className customize
let trClassName = this.props.trClassName;
if (Utils.isFunction(this.props.trClassName)) {
trClassName = this.props.trClassName(data, r);
}
if (isExpanding && this.props.expandParentClass) {
trClassName += Utils.isFunction(this.props.expandParentClass) ?
this.props.expandParentClass(data, r) :
this.props.expandParentClass;
}
const result = [ <TableRow isSelected={ selected } key={ key } className={ trClassName }
index={ r }
row={ data }
selectRow={ isSelectRowDefined ? this.props.selectRow : undefined }
enableCellEdit={ cellEdit.mode !== Const.CELL_EDIT_NONE }
onRowClick={ this.handleRowClick }
onRowDoubleClick={ this.handleRowDoubleClick }
onRowMouseOver={ this.handleRowMouseOver }
onRowMouseOut={ this.handleRowMouseOut }
onSelectRow={ this.handleSelectRow }
onExpandRow={ this.handleClickCell }
unselectableRow={ disable }
style={ trStyle }
dbClickToEdit={ cellEdit.mode === Const.CELL_EDIT_DBCLICK } >
{ this.props.expandColumnOptions.expandColumnVisible &&
this.props.expandColumnOptions.expandColumnBeforeSelectColumn &&
expandedRowColumn }
{ selectRowColumn }
{ this.props.expandColumnOptions.expandColumnVisible &&
!this.props.expandColumnOptions.expandColumnBeforeSelectColumn &&
expandedRowColumn }
{ tableColumns }
</TableRow> ];
if (haveExpandContent) {
const expandBodyClass = Utils.isFunction(this.props.expandBodyClass) ?
this.props.expandBodyClass(data, r, isExpanding) :
this.props.expandBodyClass;
result.push(
<ExpandComponent
key={ key + '-expand' }
row={ data }
className={ expandBodyClass }
bgColor={ this.props.expandRowBgColor || this.props.selectRow.bgColor || undefined }
hidden={ !isExpanding }
colSpan={ expandColSpan }
width={ "100%" }>
{ this.props.expandComponent(data) }
</ExpandComponent>
);
}
return (result);
}, this);
if (tableRows.length === 0 && !this.props.withoutNoDataText) {
const colSpan = this.props.columns.filter(c => !c.hidden).length
+ ((isSelectRowDefined && !this.props.selectRow.hideSelectColumn) ? 1 : 0)
+ (this.props.expandColumnOptions.expandColumnVisible ? 1 : 0);
tableRows = [
<TableRow key='##table-empty##' style={ trStyle }>
<td data-toggle='collapse'
colSpan={ colSpan }
className='react-bs-table-no-data'>
{ this.props.noDataText || Const.NO_DATA_TEXT }
</td>
</TableRow>
];
}
return (
<div ref='container'
className={ classSet('react-bs-container-body', this.props.bodyContainerClass) }
style={ this.props.style }>
<table className={ tableClasses }>
{ React.cloneElement(tableHeader, { ref: 'header' }) }
<tbody ref='tbody'>
{ tableRows }
</tbody>
</table>
</div>
);
}
handleCellKeyDown = (e, lastEditCell) => {
e.preventDefault();
const { keyBoardNav, onNavigateCell, cellEdit } = this.props;
let offset;
if (e.keyCode === 37) {
offset = { x: -1, y: 0 };
} else if (e.keyCode === 38) {
offset = { x: 0, y: -1 };
} else if (e.keyCode === 39 || e.keyCode === 9) {
offset = { x: 1, y: 0 };
if (e.keyCode === 9 && lastEditCell) {
offset = {
...offset,
lastEditCell
};
}
} else if (e.keyCode === 40) {
offset = { x: 0, y: 1 };
} else if (e.keyCode === 13) {
const enterToEdit = typeof keyBoardNav === 'object' ?
keyBoardNav.enterToEdit :
false;
const enterToExpand = typeof keyBoardNav === 'object' ?
keyBoardNav.enterToExpand :
false;
if (cellEdit && enterToEdit) {
this.handleEditCell(e.target.parentElement.rowIndex + 1,
e.currentTarget.cellIndex, '', e);
}
if (enterToExpand) {
this.handleClickCell(this.props.y + 1, this.props.x);
}
}
if (offset && keyBoardNav) {
onNavigateCell(offset);
}
}
handleRowMouseOut = (rowIndex, event) => {
const targetRow = this.props.data[rowIndex];
this.props.onRowMouseOut(targetRow, event);
}
handleRowMouseOver = (rowIndex, event) => {
const targetRow = this.props.data[rowIndex];
this.props.onRowMouseOver(targetRow, event);
}
handleRowClick = (rowIndex, cellIndex) => {
const { onRowClick } = this.props;
if (this._isSelectRowDefined()) cellIndex--;
if (this._isExpandColumnVisible()) cellIndex--;
onRowClick(this.props.data[rowIndex - 1], rowIndex - 1, cellIndex);
}
handleRowDoubleClick = rowIndex => {
const { onRowDoubleClick } = this.props;
const targetRow = this.props.data[rowIndex];
onRowDoubleClick(targetRow);
}
handleSelectRow = (rowIndex, isSelected, e) => {
let selectedRow;
const { data, onSelectRow } = this.props;
data.forEach((row, i) => {
if (i === rowIndex - 1) {
selectedRow = row;
return false;
}
});
onSelectRow(selectedRow, isSelected, e, rowIndex - 1);
}
handleSelectRowColumChange = (e, rowIndex) => {
if (!this.props.selectRow.clickToSelect ||
!this.props.selectRow.clickToSelectAndEditCell) {
this.handleSelectRow(
rowIndex + 1,
e.currentTarget.checked,
e);
}
}
handleClickCell = (rowIndex, columnIndex = -1) => {
const {
columns,
keyField,
expandBy,
expandableRow,
selectRow: {
clickToExpand,
hideSelectColumn
},
onlyOneExpanding
} = this.props;
const selectRowAndExpand = this._isSelectRowDefined() && !clickToExpand ? false : true;
columnIndex = this._isSelectRowDefined() && !hideSelectColumn ? columnIndex - 1 : columnIndex;
columnIndex = this._isExpandColumnVisible() ? columnIndex - 1 : columnIndex;
if (expandableRow &&
selectRowAndExpand &&
(expandBy === Const.EXPAND_BY_ROW ||
/* Below will allow expanding trigger by clicking on selection column
if configure as expanding by column */
(expandBy === Const.EXPAND_BY_COL && columnIndex < 0) ||
(expandBy === Const.EXPAND_BY_COL && columns[columnIndex].expandable))) {
let expanding = this.props.expanding;
const rowKey = this.props.data[rowIndex - 1][keyField];
const isRowExpanding = expanding.indexOf(rowKey) > -1;
if (isRowExpanding) { // collapse
expanding = expanding.filter(k => k !== rowKey);
} else { // expand
if (onlyOneExpanding) expanding = [ rowKey ];
else expanding.push(rowKey);
}
this.props.onExpand(expanding, rowKey, isRowExpanding);
}
}
handleEditCell = (rowIndex, columnIndex, action, e) => {
const { selectRow } = this.props;
const defineSelectRow = this._isSelectRowDefined();
const expandColumnVisible = this._isExpandColumnVisible();
if (defineSelectRow) {
columnIndex--;
if (selectRow.hideSelectColumn) columnIndex++;
}
if (expandColumnVisible) {
columnIndex--;
}
rowIndex--;
if (action === 'tab') {
if (defineSelectRow && !selectRow.hideSelectColumn) columnIndex++;
if (expandColumnVisible) columnIndex++;
this.handleCompleteEditCell(e.target.value, rowIndex, columnIndex - 1);
if (columnIndex >= this.props.columns.length) {
this.handleCellKeyDown(e, true);
} else {
this.handleCellKeyDown(e);
}
const { nextRIndex, nextCIndex } = this.nextEditableCell(rowIndex, columnIndex);
rowIndex = nextRIndex;
columnIndex = nextCIndex;
}
const stateObj = {
currEditCell: {
rid: rowIndex,
cid: columnIndex
}
};
if (this.props.selectRow.clickToSelectAndEditCell &&
this.props.cellEdit.mode !== Const.CELL_EDIT_DBCLICK) {
const selected = this.props.selectedRowKeys.indexOf(
this.props.data[rowIndex][this.props.keyField]) !== -1;
this.handleSelectRow(rowIndex + 1, !selected, e);
}
this.setState(() => stateObj);
}
nextEditableCell = (rIndex, cIndex) => {
const { keyField } = this.props;
let nextRIndex = rIndex;
let nextCIndex = cIndex;
let row;
let column;
do {
if (nextCIndex >= this.props.columns.length) {
nextRIndex++;
nextCIndex = 0;
}
row = this.props.data[nextRIndex];
column = this.props.columns[nextCIndex];
if (!row) break;
let editable = column.editable;
if (Utils.isFunction(column.editable)) {
editable = column.editable(column, row, nextRIndex, nextCIndex);
}
if (editable && editable.readOnly !== true &&
!column.hidden && keyField !== column.name) {
break;
} else {
nextCIndex++;
}
} while (row);
return { nextRIndex, nextCIndex };
}
handleCompleteEditCell = (newVal, rowIndex, columnIndex) => {
if (newVal !== null) {
const result = this.props.onEditCell(newVal, rowIndex, columnIndex);
if (result !== Const.AWAIT_BEFORE_CELL_EDIT) {
this.setState(() => { return { currEditCell: null }; });
}
} else {
this.setState(() => { return { currEditCell: null }; });
}
}
cancelEditCell = () => {
this.setState(() => { return { currEditCell: null }; });
}
handleClickonSelectColumn = (e, isSelect, rowIndex, row) => {
e.stopPropagation();
if (e.target.tagName === 'TD' &&
(this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell)) {
const unselectable = this.props.selectRow.unselectable || [];
if (unselectable.indexOf(row[this.props.keyField]) === -1) {
this.handleSelectRow(rowIndex + 1, isSelect, e);
this.handleClickCell(rowIndex + 1);
}
}
}
renderSelectRowColumn(selected, inputType, disabled,
CustomComponent = null, rowIndex = null, row) {
return (
<td onClick={ e => {
this.handleClickonSelectColumn(e, !selected, rowIndex, row);
} } style={ { textAlign: 'center' } }>
{ CustomComponent ?
<CustomComponent type={ inputType } checked={ selected } disabled={ disabled }
rowIndex={ rowIndex }
onChange={ e=>this.handleSelectRowColumChange(e, rowIndex) }/> :
<input type={ inputType } checked={ selected } disabled={ disabled }
onChange={ e=>this.handleSelectRowColumChange(e, rowIndex) }/>
}
</td>
);
}
renderExpandRowColumn(isExpandableRow, isExpanded, CustomComponent, rowIndex = null) {
let content = null;
if (CustomComponent) {
content = (<CustomComponent isExpandableRow={ isExpandableRow } isExpanded={ isExpanded } />);
} else if (isExpandableRow) {
content = (isExpanded ? (<span className='fa fa-minus glyphicon glyphicon-minus'></span>) :
(<span className='fa fa-plus glyphicon glyphicon-plus'></span>) );
} else {
content = ' ';
}
return (
<td
className='react-bs-table-expand-cell'
onClick={ () => this.handleClickCell(rowIndex + 1) }>
{ content }
</td>
);
}
_isSelectRowDefined() {
return this.props.selectRow.mode === Const.ROW_SELECT_SINGLE ||
this.props.selectRow.mode === Const.ROW_SELECT_MULTI;
}
_isExpandColumnVisible() {
return this.props.expandColumnOptions.expandColumnVisible;
}
getHeaderColGrouop = () => {
return this.refs.header.childNodes;
}
}
TableBody.propTypes = {
version: PropTypes.string,
data: PropTypes.array,
columns: PropTypes.array,
striped: PropTypes.bool,
bordered: PropTypes.bool,
hover: PropTypes.bool,
condensed: PropTypes.bool,
keyField: PropTypes.string,
selectedRowKeys: PropTypes.array,
onRowClick: PropTypes.func,
onRowDoubleClick: PropTypes.func,
onSelectRow: PropTypes.func,
noDataText: PropTypes.oneOfType([ PropTypes.string, PropTypes.object ]),
withoutNoDataText: PropTypes.bool,
style: PropTypes.object,
tableBodyClass: PropTypes.string,
bodyContainerClass: PropTypes.string,
expandableRow: PropTypes.func,
expandComponent: PropTypes.func,
expandRowBgColor: PropTypes.string,
expandBy: PropTypes.string,
expanding: PropTypes.array,
onExpand: PropTypes.func,
expandBodyClass: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]),
expandParentClass: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]),
onlyOneExpanding: PropTypes.bool,
beforeShowError: PropTypes.func,
keyBoardNav: PropTypes.oneOfType([ PropTypes.bool, PropTypes.object ]),
x: PropTypes.number,
y: PropTypes.number,
onNavigateCell: PropTypes.func,
withoutTabIndex: PropTypes.bool
};
export default TableBody;
|
src/components/Search/Search.js | nambawan/g-old | // heavily inspired by https://github.com/grommet/grommet/blob/master/src/js/components/Search.js
import React from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import cn from 'classnames';
import withStyles from 'isomorphic-style-loader/withStyles';
import s from './Search.css';
import Drop from '../Drop';
const onSink = event => {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
};
const renderLabel = suggestion => {
if (typeof suggestion === 'object') {
return suggestion.label || suggestion.value;
}
return suggestion;
};
class Search extends React.Component {
static contextTypes = {
intl: PropTypes.object,
insertCss: PropTypes.func,
};
static propTypes = {
dropAlign: PropTypes.shape(),
id: PropTypes.string,
onFocus: PropTypes.func,
onDOMChange: PropTypes.func.isRequired,
onSelect: PropTypes.func.isRequired,
placeHolder: PropTypes.string,
suggestions: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.shape({
label: PropTypes.node,
value: PropTypes.any,
}),
PropTypes.string,
]),
),
value: PropTypes.string,
};
static defaultProps = {
placeHolder: null,
suggestions: null,
value: null,
dropAlign: null,
id: null,
onFocus: null,
};
constructor(props, context) {
super(props, context);
this.onAddDrop = this.onAddDrop.bind(this);
this.onRemoveDrop = this.onRemoveDrop.bind(this);
this.onChangeInput = this.onChangeInput.bind(this);
this.onClickBody = this.onClickBody.bind(this);
this.onClickSuggestion = this.onClickSuggestion.bind(this);
this.fireDOMChange = this.fireDOMChange.bind(this);
this.onFocusInput = this.onFocusInput.bind(this);
this.state = {
activeSuggestionIndex: -1,
align: 'left',
dropActive: false,
};
}
componentWillReceiveProps(nextProps) {
const { dropActive } = this.state;
if (
nextProps.suggestions &&
nextProps.suggestions.length > 0 &&
!dropActive &&
this.inputRef === document.activeElement
) {
this.setState({ dropActive: true });
}
}
componentDidUpdate(prevProps, prevState) {
const { dropAlign } = this.props;
const { dropActive } = this.state;
if (!dropActive && prevState.dropActive) {
document.removeEventListener('click', this.onClickBody);
if (this.drop) {
this.drop.remove();
this.drop = undefined;
}
}
if (dropActive && !prevState.dropActive) {
document.addEventListener('click', this.onClickBody);
let baseElement;
if (this.controlRef) {
baseElement = findDOMNode(this.controlRef);
} else {
baseElement = this.inputRef;
}
const align = dropAlign || {
top: 'bottom',
left: 'left',
};
this.drop = new Drop(baseElement, this.renderDropContent(), {
align,
className: s.drop,
responsive: false, // so suggestion changes don't re-align
context: this.context,
});
this.inputRef.focus();
} else if (this.drop) {
this.drop.render(this.renderDropContent());
}
}
componentWillUnmount() {
document.removeEventListener('click', this.onClickBody);
if (this.drop) {
this.drop.remove();
}
}
onClickBody(event) {
// don't close drop when clicking on input
if (event.target !== this.inputRef) {
this.onRemoveDrop();
}
}
// eslint-disable-next-line no-unused-vars
onChangeInput(event) {
const { onDOMChange } = this.props;
this.setState({ activeSuggestionIndex: -1, announceChange: true });
if (onDOMChange) {
this.fireDOMChange();
}
}
onClickSuggestion(suggestion) {
const { onSelect } = this.props;
this.onRemoveDrop();
if (onSelect) {
onSelect(
{
target: this.inputRef || this.controlRef,
suggestion,
},
true,
);
}
}
onAddDrop() {
this.setState({ dropActive: true, activeSuggestionIndex: -1 });
}
onRemoveDrop() {
this.setState({ dropActive: false });
}
onFocusInput(event) {
const { onFocus, suggestions } = this.props;
if (onFocus) {
onFocus(event);
}
if (suggestions && suggestions.length > 0) {
this.onAddDrop();
}
}
fireDOMChange() {
const { onDOMChange } = this.props;
let event;
try {
event = new Event('change', {
bubbles: true,
cancelable: true,
});
} catch (e) {
// IE11 workaround.
event = document.createEvent('Event');
event.initEvent('change', true, true);
}
const target = this.inputRef;
target.dispatchEvent(event);
onDOMChange(event);
}
renderDropContent() {
const { suggestions } = this.props;
const { activeSuggestionIndex } = this.state;
let suggestionsNode;
if (suggestions) {
/* eslint-disable react/no-array-index-key */
suggestionsNode = suggestions.map(
(suggestion, index) => (
<div
key={index}
className={cn(
s.searchSuggestion,
index === activeSuggestionIndex ? s.active : null,
)}
tabIndex="-1"
role="button"
onClick={this.onClickSuggestion.bind(this, suggestion)} // eslint-disable-line
>
{renderLabel(suggestion)}
</div>
),
this,
);
/* eslint-enable react/no-array-index-key */
suggestionsNode = <div key="suggestions">{suggestionsNode}</div>;
}
const contents = [
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div key="contents" onClick={onSink}>
{suggestionsNode}
</div>,
];
return <div className={s.searchDrop}>{contents}</div>;
}
render() {
const { id, placeHolder, value } = this.props;
return (
<div className={s.search}>
<input
ref={ref => (this.inputRef = ref)}
type="search"
id={id}
placeholder={placeHolder}
autoComplete="off"
value={renderLabel(value)}
className={s.searchInput}
onChange={this.onChangeInput}
onFocus={this.onFocusInput}
/>
<svg
className={s.searchIcon}
version="1.1"
viewBox="0 0 24 24"
width="24px"
height="24px"
role="img"
aria-label="search"
>
<path
fill="none"
stroke="#000"
strokeWidth="2"
d="M15,15 L22,22 L15,15 Z M9.5,17 C13.6421356,17 17,13.6421356 17,9.5 C17,5.35786438 13.6421356,2 9.5,2 C5.35786438,2 2,5.35786438 2,9.5 C2,13.6421356 5.35786438,17 9.5,17 Z"
/>
</svg>
</div>
);
}
}
export default withStyles(s)(Search);
|
packages/material-ui-icons/src/ThumbDown.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v2c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z" /></React.Fragment>
, 'ThumbDown');
|
ajax/libs/react-data-grid/0.12.27/react-data-grid-with-addons.min.js | sashberd/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react")):e.ReactDataGrid=t(e.React)}(this,function(e){return function(e){function t(s){if(r[s])return r[s].exports;var o=r[s]={exports:{},id:s,loaded:!1};return e[s].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";e.exports=r(43),e.exports.Editors=r(69),e.exports.Formatters=r(71),e.exports.Toolbar=r(72),e.exports.Row=r(11)},function(t,r){t.exports=e},function(e,t,r){"use strict";var s=(r(17)["default"],r(1)),o={name:s.PropTypes.string.isRequired,key:s.PropTypes.string.isRequired,width:s.PropTypes.number.isRequired};e.exports=o},function(e,t,r){"use strict";var s=r(14)["default"];t["default"]=s||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},t.__esModule=!0},function(e,t,r){function s(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+s.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}var o,n;"undefined"!=typeof e&&e.exports&&(e.exports=s),o=[],n=function(){return s}.apply(t,o),!(void 0!==n&&(e.exports=n))},function(e,t,r){(function(t){"use strict";function s(e,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(!e.ref,"You are calling cloneWithProps() on a child with a ref. This is dangerous because you're creating a new child which will not be added as a ref to its parent."):null);var s=n.mergeProps(r,e.props);return!s.hasOwnProperty(a)&&e.props.hasOwnProperty(a)&&(s.children=e.props.children),o.createElement(e.type,s)}var o=r(61),n=r(62),i=r(65),l=r(15),a=i({children:null});e.exports=s}).call(t,r(8))},function(e,t){"use strict";e.exports={getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},spliceColumn:function(e,t,r){return Array.isArray(e.columns)?e.columns.splice(t,1,r):"undefined"!=typeof Immutable&&(e.columns=e.columns.splice(t,1,r)),e},getSize:function(e){return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0}}},function(e,t){function r(e){return function(){return e}}function s(){}s.thatReturns=r,s.thatReturnsFalse=r(!1),s.thatReturnsTrue=r(!0),s.thatReturnsNull=r(null),s.thatReturnsThis=function(){return this},s.thatReturnsArgument=function(e){return e},e.exports=s},function(e,t){function r(){u=!1,i.length?a=i.concat(a):c=-1,a.length&&s()}function s(){if(!u){var e=setTimeout(r);u=!0;for(var t=a.length;t;){for(i=a,a=[];++c<t;)i&&i[c].run();c=-1,t=a.length}i=null,u=!1,clearTimeout(e)}}function o(e,t){this.fun=e,this.array=t}function n(){}var i,l=e.exports={},a=[],u=!1,c=-1;l.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];a.push(new o(e,t)),1!==a.length||u||setTimeout(s,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=n,l.addListener=n,l.once=n,l.off=n,l.removeListener=n,l.removeAllListeners=n,l.emit=n,l.binding=function(e){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(e){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},function(e,t,r){"use strict";var s=r(1),o=r(7),n=r(13),i={metricsComputator:s.PropTypes.object},l={childContextTypes:i,getChildContext:function(){return{metricsComputator:this}},getMetricImpl:function(e){return this._DOMMetrics.metrics[e].value},registerMetricsImpl:function(e,t){var r={},s=this._DOMMetrics;for(var o in t){if(void 0!==s.metrics[o])throw new Error("DOM metric "+o+" is already defined");s.metrics[o]={component:e,computator:t[o].bind(e)},r[o]=this.getMetricImpl.bind(null,o)}return-1===s.components.indexOf(e)&&s.components.push(e),r},unregisterMetricsFor:function(e){var t=this._DOMMetrics,r=t.components.indexOf(e);if(r>-1){t.components.splice(r,1);var s,o={};for(s in t.metrics)t.metrics[s].component===e&&(o[s]=!0);for(s in o)delete t.metrics[s]}},updateMetrics:function(){var e=this._DOMMetrics,t=!1;for(var r in e.metrics){var s=e.metrics[r].computator();s!==e.metrics[r].value&&(t=!0),e.metrics[r].value=s}if(t)for(var o=0,n=e.components.length;n>o;o++)e.components[o].metricsUpdated&&e.components[o].metricsUpdated()},componentWillMount:function(){this._DOMMetrics={metrics:{},components:[]}},componentDidMount:function(){window.addEventListener?window.addEventListener("resize",this.updateMetrics):window.attachEvent("resize",this.updateMetrics),this.updateMetrics()},componentWillUnmount:function(){window.removeEventListener("resize",this.updateMetrics)}},a={contextTypes:i,componentWillMount:function(){if(this.DOMMetrics){this._DOMMetricsDefs=n(this.DOMMetrics),this.DOMMetrics={};for(var e in this._DOMMetricsDefs)this.DOMMetrics[e]=o}},componentDidMount:function(){this.DOMMetrics&&(this.DOMMetrics=this.registerMetrics(this._DOMMetricsDefs))},componentWillUnmount:function(){return this.registerMetricsImpl?void(this.hasOwnProperty("DOMMetrics")&&delete this.DOMMetrics):this.context.metricsComputator.unregisterMetricsFor(this)},registerMetrics:function(e){return this.registerMetricsImpl?this.registerMetricsImpl(this,e):this.context.metricsComputator.registerMetricsImpl(this,e)},getMetric:function(e){return this.getMetricImpl?this.getMetricImpl(e):this.context.metricsComputator.getMetricImpl(e)}};e.exports={MetricsComputatorMixin:l,MetricsMixin:a}},function(e,t,r){"use strict";var s=(r(1),{onKeyDown:function(e){if(this.isCtrlKeyHeldDown(e))this.checkAndCall("onPressKeyWithCtrl",e);else if(this.isKeyExplicitlyHandled(e.key)){var t="onPress"+e.key;this.checkAndCall(t,e)}else this.isKeyPrintable(e.keyCode)&&this.checkAndCall("onPressChar",e)},isKeyPrintable:function(e){var t=e>47&&58>e||32==e||13==e||e>64&&91>e||e>95&&112>e||e>185&&193>e||e>218&&223>e;return t},isKeyExplicitlyHandled:function(e){return"function"==typeof this["onPress"+e]},isCtrlKeyHeldDown:function(e){return e.ctrlKey===!0&&"Control"!==e.key},checkAndCall:function(e,t){"function"==typeof this[e]&&this[e](t)}});e.exports=s},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=r(4),i=r(22),l=(r(5),r(12)),a=r(6),u=o.createClass({displayName:"Row",propTypes:{height:o.PropTypes.number.isRequired,columns:o.PropTypes.oneOfType([o.PropTypes.object,o.PropTypes.array]).isRequired,row:o.PropTypes.object.isRequired,cellRenderer:o.PropTypes.func,isSelected:o.PropTypes.bool,idx:o.PropTypes.number.isRequired,expandedRows:o.PropTypes.arrayOf(o.PropTypes.object)},mixins:[a],render:function(){var e=n("react-grid-Row","react-grid-Row--${this.props.idx % 2 === 0 ? 'even' : 'odd'}"),t={height:this.getRowHeight(this.props),overflow:"hidden"},r=this.getCells();return o.createElement("div",s({},this.props,{className:e,style:t,onDragEnter:this.handleDragEnter}),o.isValidElement(this.props.row)?this.props.row:r)},getCells:function(){var e=this,t=[],r=[],s=this.getSelectedColumn();return this.props.columns.forEach(function(n,i){var l=e.props.cellRenderer,a=o.createElement(l,{ref:i,key:i,idx:i,rowIdx:e.props.idx,value:e.getCellValue(n.key||i),column:n,height:e.getRowHeight(),formatter:n.formatter,cellMetaData:e.props.cellMetaData,rowData:e.props.row,selectedColumn:s,isRowSelected:e.props.isSelected});n.locked?r.push(a):t.push(a)}),t.concat(r)},getRowHeight:function(){var e=this.props.expandedRows||null;if(e&&this.props.key){var t=e[this.props.key]||null;if(t)return t.height}return this.props.height},getCellValue:function(e){var t;return"select-row"===e?this.props.isSelected:t="function"==typeof this.props.row.get?this.props.row.get(e):this.props.row[e]},getRowData:function(){return this.props.row.toJSON?this.props.row.toJSON():this.props.row},getDefaultProps:function(){return{cellRenderer:i,isSelected:!1,height:35}},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,s){if(r.locked){if(!t.refs[s])return;t.refs[s].setScrollLeft(e)}})},doesRowContainSelectedCell:function(e){var t=e.cellMetaData.selected;return t&&t.rowIdx===e.idx?!0:!1},willRowBeDraggedOver:function(e){var t=e.cellMetaData.dragged;return null!=t&&(t.rowIdx>=0||t.complete===!0)},hasRowBeenCopied:function(){var e=this.props.cellMetaData.copied;return null!=e&&e.rowIdx===this.props.idx},shouldComponentUpdate:function(e,t){return!l.sameColumns(this.props.columns,e.columns,l.sameColumn)||this.doesRowContainSelectedCell(this.props)||this.doesRowContainSelectedCell(e)||this.willRowBeDraggedOver(e)||e.row!==this.props.row||this.hasRowBeenCopied()||this.props.isSelected!==e.isSelected||e.height!==this.props.height},handleDragEnter:function(){var e=this.props.cellMetaData.handleDragEnterRow;e&&e(this.props.idx)},getSelectedColumn:function(){var e=this.props.cellMetaData.selected;return e&&e.idx?this.getColumn(this.props.columns,e.idx):void 0}});e.exports=u},function(e,t,r){"use strict";function s(e){var t=n(e.columns,e.totalWidth),r=t.filter(function(e){return e.width}).reduce(function(e,t){return e-t.width},e.totalWidth),s=t.filter(function(e){return e.width}).reduce(function(e,t){return e+t.width},0);return t=i(t,r,e.minColumnWidth),t=o(t),{columns:t,width:s,totalWidth:e.totalWidth,minColumnWidth:e.minColumnWidth}}function o(e){var t=0;return e.map(function(e){return e.left=t,t+=e.width,e})}function n(e,t){return e.map(function(e){var r=p({},e);return e.width&&/^([0-9]+)%$/.exec(e.width.toString())&&(r.width=Math.floor(e.width/100*t)),r})}function i(e,t,r){var s=e.filter(function(e){return!e.width});return e.map(function(e,o,n){return e.width||(0>=t?e.width=r:e.width=Math.floor(t/f.getSize(s))),e})}function l(e,t,r){var o=f.getColumn(e.columns,t);e=h(e),e.columns=e.columns.slice(0);var n=h(o);return n.width=Math.max(r,e.minColumnWidth),e=f.spliceColumn(e,t,n),s(e)}function a(e,t){return"undefined"!=typeof Immutable&&e instanceof Immutable.List&&t instanceof Immutable.List}function u(e,t,r){var s,o,n,i={},l={};if(f.getSize(e)!==f.getSize(t))return!1;for(s=0,o=f.getSize(e);o>s;s++)n=e[s],i[n.key]=n;for(s=0,o=f.getSize(t);o>s;s++){n=t[s],l[n.key]=n;var a=i[n.key];if(void 0===a||!r(a,n))return!1}for(s=0,o=f.getSize(e);o>s;s++){n=e[s];var u=l[n.key];if(void 0===u)return!1}return!0}function c(e,t,r){return a(e,t)?e===t:u(e,t,r)}var p=r(14)["default"],h=r(13),d=(r(1).isValidElement,r(26)),f=r(6);e.exports={recalculate:s,resizeColumn:l,sameColumn:d,sameColumns:c}},function(e,t){"use strict";function r(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}e.exports=r},function(e,t,r){e.exports={"default":r(46),__esModule:!0}},function(e,t,r){(function(t){"use strict";var s=r(7),o=s;"production"!==t.env.NODE_ENV&&(o=function(e,t){for(var r=[],s=2,o=arguments.length;o>s;s++)r.push(arguments[s]);if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(!e){var n=0;console.warn("Warning: "+t.replace(/%s/g,function(){return r[n++]}))}}),e.exports=o}).call(t,r(8))},function(e,t){"use strict";var r=function(e){var t={};return e&&"[object Function]"===t.toString.call(e)};e.exports=r},function(e,t){"use strict";t["default"]=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.__esModule=!0},function(e,t){var r=e.exports={version:"1.2.6"};"number"==typeof __e&&(__e=r)},function(e,t){"use strict";function r(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var s,o,n=r(e),i=1;i<arguments.length;i++){s=arguments[i],o=Object.keys(Object(s));for(var l=0;l<o.length;l++)n[o[l]]=s[o[l]]}return n}},function(e,t){function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var r=Object(e),s=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var n=arguments[o];if(null!=n){var i=Object(n);for(var l in i)s.call(i,l)&&(r[l]=i[l])}}return r}e.exports=r},function(e,t){"use strict";function r(e,t){if(e===t)return!0;var r;for(r in e)if(e.hasOwnProperty(r)&&(!t.hasOwnProperty(r)||e[r]!==t[r]))return!1;for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}e.exports=r},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=r(4),i=r(5),l=r(42),a=r(2),u=r(16),c=r(34),p=o.createClass({displayName:"Cell",propTypes:{rowIdx:o.PropTypes.number.isRequired,idx:o.PropTypes.number.isRequired,selected:o.PropTypes.shape({idx:o.PropTypes.number.isRequired}),tabIndex:o.PropTypes.number,ref:o.PropTypes.string,column:o.PropTypes.shape(a).isRequired,value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired,isExpanded:o.PropTypes.bool,cellMetaData:o.PropTypes.shape(c).isRequired,handleDragStart:o.PropTypes.func,className:o.PropTypes.string,rowData:o.PropTypes.object.isRequired},getDefaultProps:function(){return{tabIndex:-1,ref:"cell",isExpanded:!1}},getInitialState:function(){return{isRowChanging:!1,isCellValueChanging:!1}},componentDidMount:function(){this.checkFocus()},componentDidUpdate:function(e,t){this.checkFocus();var r=this.props.cellMetaData.dragged;r&&r.complete===!0&&this.props.cellMetaData.handleTerminateDrag(),this.state.isRowChanging&&null!=this.props.selectedColumn&&this.applyUpdateClass()},componentWillReceiveProps:function(e){this.setState({isRowChanging:this.props.rowData!==e.rowData,isCellValueChanging:this.props.value!==e.value})},shouldComponentUpdate:function(e,t){return this.props.column.width!==e.column.width||this.props.column.left!==e.column.left||this.props.rowData!==e.rowData||this.props.height!==e.height||this.props.rowIdx!==e.rowIdx||this.isCellSelectionChanging(e)||this.isDraggedCellChanging(e)||this.isCopyCellChanging(e)||this.props.isRowSelected!==e.isRowSelected||this.isSelected()||this.props.value!==e.value},getStyle:function(){var e={position:"absolute",width:this.props.column.width,height:this.props.height,left:this.props.column.left};return e},render:function(){var e=this.getStyle(),t=this.getCellClass(),r=this.renderCellContent({value:this.props.value,column:this.props.column,rowIdx:this.props.rowIdx,isExpanded:this.props.isExpanded});return o.createElement("div",s({},this.props,{className:t,style:e,onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick}),r,o.createElement("div",{className:"drag-handle",draggable:"true"}))},renderCellContent:function(e){var t,r=this.getFormatter();return o.isValidElement(r)?(e.dependentValues=this.getFormatterDependencies(),t=i(r,e)):t=u(r)?o.createElement(r,{value:this.props.value,dependentValues:this.getFormatterDependencies()}):o.createElement(h,{value:this.props.value}),o.createElement("div",{ref:"cell",className:"react-grid-Cell__value"},t," ",this.props.cellControls)},isColumnSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.idx===this.props.idx},isSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.rowIdx===this.props.rowIdx&&e.selected.idx===this.props.idx},isActive:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:this.isSelected()&&e.selected.active===!0},isCellSelectionChanging:function(e){var t=this.props.cellMetaData;if(null==t||null==t.selected)return!1;var r=e.cellMetaData.selected;return t.selected&&r?this.props.idx===r.idx||this.props.idx===t.selected.idx:!0},getFormatter:function(){var e=this.props.column;return this.isActive()?o.createElement(l,{rowData:this.getRowData(),rowIdx:this.props.rowIdx,idx:this.props.idx,cellMetaData:this.props.cellMetaData,column:e,height:this.props.height}):this.props.column.formatter},getRowData:function(){return this.props.rowData.toJSON?this.props.rowData.toJSON():this.props.rowData},getFormatterDependencies:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.getRowData(),this.props.column):void 0},onCellClick:function(e){var t=this.props.cellMetaData;null!=t&&null!=t.onCellClick&&t.onCellClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onCellDoubleClick:function(e){var t=this.props.cellMetaData;null!=t&&null!=t.onCellDoubleClick&&t.onCellDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},checkFocus:function(){this.isSelected()&&!this.isActive()&&this.getDOMNode().focus()},getCellClass:function(){var e=n(this.props.column.cellClass,"react-grid-Cell",this.props.className,this.props.column.locked?"react-grid-Cell--locked":null),t=n({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 n(e,t)},getUpdateCellClass:function(){return this.props.column.getUpdateCellClass?this.props.column.getUpdateCellClass(this.props.selectedColumn,this.props.column,this.state.isCellValueChanging):""},applyUpdateClass:function(){var e=this.getUpdateCellClass();if(null!=e&&""!=e){var t=this.getDOMNode();t.classList?(t.classList.remove(e),t.classList.add(e)):-1===t.className.indexOf(e)&&(t.className=t.className+" "+e)}},setScrollLeft:function(e){var t=this;if(t.isMounted()){var r=this.getDOMNode(),s="translate3d("+e+"px, 0px, 0px)";r.style.webkitTransform=s,r.style.transform=s}},isCopied:function(){var e=this.props.cellMetaData.copied;return e&&e.rowIdx===this.props.rowIdx&&e.idx===this.props.idx},isDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&e.overRowIdx===this.props.rowIdx&&e.idx===this.props.idx},wasDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&(e.overRowIdx<this.props.rowIdx&&this.props.rowIdx<e.rowIdx||e.overRowIdx>this.props.rowIdx&&this.props.rowIdx>e.rowIdx)&&e.idx===this.props.idx},isDraggedCellChanging:function(e){var t,r=this.props.cellMetaData.dragged,s=e.cellMetaData.dragged;return r?t=s&&this.props.idx===s.idx||r&&this.props.idx===r.idx:!1},isCopyCellChanging:function(e){var t,r=this.props.cellMetaData.copied,s=e.cellMetaData.copied;return r?t=s&&this.props.idx===s.idx||r&&this.props.idx===r.idx:!1},isDraggedOverUpwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx<e.rowIdx},isDraggedOverDownwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx>e.rowIdx}}),h=o.createClass({displayName:"SimpleCellFormatter",propTypes:{value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired},render:function(){return o.createElement("span",null,this.props.value)},shouldComponentUpdate:function(e,t){return e.value!==this.props.value}});e.exports=p},function(e,t,r){"use strict";var s=r(1),o=s.createClass({displayName:"CheckboxEditor",PropTypes:{value:s.PropTypes.bool.isRequired,rowIdx:s.PropTypes.number.isRequired,column:s.PropTypes.shape({key:s.PropTypes.string.isRequired,onCellChange:s.PropTypes.func.isRequired}).isRequired},render:function(){var e=null!=this.props.value?this.props.value:!1;return s.createElement("input",{className:"react-grid-CheckBox",type:"checkbox",checked:e,onClick:this.handleChange})},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,e)}});e.exports=o},function(e,t,r){"use strict";var s=r(1),o=(r(10),r(2)),n=s.createClass({displayName:"SimpleTextEditor",propTypes:{value:s.PropTypes.any.isRequired,onBlur:s.PropTypes.func,column:s.PropTypes.shape(o).isRequired},getValue:function(){var e={};return e[this.props.column.key]=this.refs.input.getDOMNode().value,e},getInputNode:function(){return this.getDOMNode()},render:function(){return s.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})}});e.exports=n},function(e,t,r){"use strict";var s=r(1),o=r(4),n=s.PropTypes,i=r(5),l=r(21),a=r(7),u=r(37),c=r(11),p=(r(2),s.createClass({displayName:"Canvas",mixins:[u],propTypes:{rowRenderer:n.oneOfType([n.func,n.element]),rowHeight:n.number.isRequired,height:n.number.isRequired,displayStart:n.number.isRequired,displayEnd:n.number.isRequired,rowsCount:n.number.isRequired,rowGetter:n.oneOfType([n.func.isRequired,n.array.isRequired]),onRows:n.func,columns:n.oneOfType([n.object,n.array]).isRequired},render:function(){var e=this,t=this.state.displayStart,r=this.state.displayEnd,n=this.props.rowHeight,i=this.props.rowsCount,l=this.getRows(t,r).map(function(r,s){return e.renderRow({key:t+s,ref:s,idx:t+s,row:r,height:n,columns:e.props.columns,isSelected:e.isRowSelected(t+s),expandedRows:e.props.expandedRows,cellMetaData:e.props.cellMetaData})});this._currentRowsLength=l.length,t>0&&l.unshift(this.renderPlaceholder("top",t*n)),i-r>0&&l.push(this.renderPlaceholder("bottom",(i-r)*n));var a=0;if(this.isMounted()){var u=this.getDOMNode();a=u.offsetWidth-u.clientWidth}var c={position:"absolute",top:0,left:0,overflowX:"auto",overflowY:"scroll",width:this.props.totalWidth+a,height:this.props.height,transform:"translate3d(0, 0, 0)"};return s.createElement("div",{style:c,onScroll:this.onScroll,className:o("react-grid-Canvas",this.props.className,{opaque:this.props.cellMetaData.selected&&this.props.cellMetaData.selected.active})},s.createElement("div",{style:{width:this.props.width,overflow:"hidden"}},l))},renderRow:function(e){var t=this.props.rowRenderer;return"function"==typeof t?s.createElement(t,e):s.isValidElement(this.props.rowRenderer)?i(this.props.rowRenderer,e):void 0},renderPlaceholder:function(e,t){return s.createElement("div",{key:e,style:{height:t}},this.props.columns.map(function(e,t){return s.createElement("div",{style:{width:e.width},key:t})}))},getDefaultProps:function(){return{rowRenderer:c,onRows:a}},isRowSelected:function(e){return this.props.selectedRows&&this.props.selectedRows[e]===!0},_currentRowsLength:0,_currentRowsRange:{start:0,end:0},_scroll:{scrollTop:0,scrollLeft:0},getInitialState:function(){return{shouldUpdate:!0,displayStart:this.props.displayStart,displayEnd:this.props.displayEnd}},componentWillMount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidMount:function(){this.onRows()},componentDidUpdate:function(e){this._scroll!=={start:0,end:0}&&this.setScrollLeft(this._scroll.scrollLeft),this.onRows()},componentWillUnmount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentWillReceiveProps:function(e){e.rowsCount>this.props.rowsCount&&(this.getDOMNode().scrollTop=e.rowsCount*this.props.rowHeight);var t=!(e.visibleStart>this.state.displayStart&&e.visibleEnd<this.state.displayEnd&&e.rowsCount===this.props.rowsCount&&e.rowHeight===this.props.rowHeight&&e.columns===this.props.columns&&e.width===this.props.width&&e.cellMetaData===this.props.cellMetaData&&l(e.style,this.props.style));t?this.setState({shouldUpdate:!0,displayStart:e.displayStart,displayEnd:e.displayEnd}):this.setState({shouldUpdate:!1})},shouldComponentUpdate:function(e,t){return!t||t.shouldUpdate},onRows:function(){this._currentRowsRange!=={start:0,end:0}&&(this.props.onRows(this._currentRowsRange),this._currentRowsRange={start:0,end:0})},getRows:function(e,t){if(this._currentRowsRange={start:e,end:t},Array.isArray(this.props.rowGetter))return this.props.rowGetter.slice(e,t);for(var r=[],s=e;t>s;s++)r.push(this.props.rowGetter(s));return r},setScrollLeft:function(e){if(0!==this._currentRowsLength){if(!this.refs)return;for(var t=0,r=this._currentRowsLength;r>t;t++)this.refs[t]&&this.refs[t].setScrollLeft&&this.refs[t].setScrollLeft(e)}},getScroll:function(){var e=this.getDOMNode(),t=e.scrollTop,r=e.scrollLeft;return{scrollTop:t,scrollLeft:r}},onScroll:function(e){this.appendScrollShim();var t=e.target,r=t.scrollTop,s=t.scrollLeft,o={scrollTop:r,scrollLeft:s};this._scroll=o,this.props.onScroll(o)}}));e.exports=p},function(e,t,r){"use strict";var s=r(1).isValidElement;e.exports=function(e,t){var r;for(r in e)if(e.hasOwnProperty(r)){if("function"==typeof e[r]&&"function"==typeof t[r]||s(e[r])&&s(t[r]))continue;if(!t.hasOwnProperty(r)||e[r]!==t[r])return!1}for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}},function(e,t,r){"use strict";var s=r(17)["default"],o=r(12),n=r(9);Object.assign=r(19);var i=r(1).PropTypes,l=r(6),a=function u(){s(this,u)};e.exports={mixins:[n.MetricsMixin],propTypes:{columns:i.arrayOf(a),minColumnWidth:i.number,columnEquality:i.func},DOMMetrics:{gridWidth:function(){var e=0,t=this.getDOMNode();if(t.offsetWidth>0)e=t.offsetWidth-2;else if(this.isMounted()&&null==this.getDOMNode().parentOffset&&this.props.columns)for(var r=0,s=this.props.columns.length;s>r;r++)e+=this.props.columns[r].width;return e}},getDefaultProps:function(){return{minColumnWidth:80,columnEquality:o.sameColumn}},componentWillReceiveProps:function(e){if(e.columns&&!o.sameColumns(this.props.columns,e.columns,this.props.columnEquality)){var t=this.createColumnMetrics();this.setState({columnMetrics:t})}},getTotalWidth:function(){var e=0;return e=this.isMounted()&&this.getDOMNode().parentOffset?this.DOMMetrics.gridWidth():l.getSize(this.props.columns)*this.props.minColumnWidth},getColumnMetricsType:function(e){var t=this.getTotalWidth(),r={columns:e.columns,totalWidth:t,minColumnWidth:e.minColumnWidth},s=o.recalculate(r);return s},getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},getSize:function(){var e=this.state.columnMetrics.columns;return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0},metricsUpdated:function(){var e=this.createColumnMetrics();this.setState({columnMetrics:e})},createColumnMetrics:function(e){var t=this.setupGridColumns();return this.getColumnMetricsType({columns:t,minColumnWidth:this.props.minColumnWidth},e)},onColumnResize:function(e,t){var r=o.resizeColumn(this.state.columnMetrics,e,t);this.setState({columnMetrics:r})}}},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=o.PropTypes,i=r(7),l=o.createClass({displayName:"Draggable",propTypes:{onDragStart:n.func,onDragEnd:n.func,onDrag:n.func,component:n.oneOfType([n.func,n.constructor])},render:function(){this.props.component;return o.createElement("div",s({},this.props,{onMouseDown:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))},getDefaultProps:function(){return{onDragStart:i.thatReturnsTrue,onDragEnd:i,onDrag:i}},getInitialState:function(){return{drag:null}},onMouseDown:function(e){var t=this.props.onDragStart(e);(null!==t||0===e.button)&&(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},componentWillUnmount:function(){this.cleanUp()},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove)}});e.exports=l},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=o.PropTypes,i=r(31),l=r(38),a=(r(2),r(30)),u=r(9),c=o.createClass({displayName:"Grid",propTypes:{rowGetter:n.oneOfType([n.array,n.func]).isRequired,columns:n.oneOfType([n.array,n.object]),minHeight:n.number,headerRows:n.oneOfType([n.array,n.func]),rowHeight:n.number,rowRenderer:n.func,expandedRows:n.oneOfType([n.array,n.func]),selectedRows:n.oneOfType([n.array,n.func]),rowsCount:n.number,onRows:n.func,sortColumn:o.PropTypes.string,sortDirection:o.PropTypes.oneOf(["ASC","DESC","NONE"]),rowOffsetHeight:n.number.isRequired,onViewportKeydown:n.func.isRequired,onViewportDragStart:n.func.isRequired,onViewportDragEnd:n.func.isRequired,onViewportDoubleClick:n.func.isRequired},mixins:[a,u.MetricsComputatorMixin],getStyle:function(){return{overflow:"hidden",outline:0,position:"relative",minHeight:this.props.minHeight}},render:function(){var e=this.props.headerRows||[{ref:"row"}];return o.createElement("div",s({},this.props,{style:this.getStyle(),className:"react-grid-Grid"}),o.createElement(i,{ref:"header",columnMetrics:this.props.columnMetrics,onColumnResize:this.props.onColumnResize,height:this.props.rowHeight,totalWidth:this.props.totalWidth,headerRows:e,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort}),o.createElement("div",{ref:"viewPortContainer",onKeyDown:this.props.onViewportKeydown,onDoubleClick:this.props.onViewportDoubleClick,onDragStart:this.props.onViewportDragStart,onDragEnd:this.props.onViewportDragEnd},o.createElement(l,{ref:"viewport",width:this.props.columnMetrics.width,rowHeight:this.props.rowHeight,rowRenderer:this.props.rowRenderer,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columnMetrics:this.props.columnMetrics,totalWidth:this.props.totalWidth,onScroll:this.onScroll,onRows:this.props.onRows,cellMetaData:this.props.cellMetaData,rowOffsetHeight:this.props.rowOffsetHeight||this.props.rowHeight*e.length,minHeight:this.props.minHeight})))},getDefaultProps:function(){return{rowHeight:35,minHeight:350}}});e.exports=c},function(e,t){"use strict";e.exports={componentDidMount:function(){this._scrollLeft=this.refs.viewport.getScroll().scrollLeft,this._onScroll()},componentDidUpdate:function(){this._onScroll()},componentWillMount:function(){this._scrollLeft=void 0},componentWillUnmount:function(){this._scrollLeft=void 0},onScroll:function(e){this._scrollLeft!==e.scrollLeft&&(this._scrollLeft=e.scrollLeft,this._onScroll())},_onScroll:function(){void 0!==this._scrollLeft&&(this.refs.header.setScrollLeft(this._scrollLeft),this.refs.viewport.setScrollLeft(this._scrollLeft))}}},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=r(4),i=r(13),l=r(12),a=r(6),u=r(33),c=o.createClass({displayName:"Header",propTypes:{columnMetrics:o.PropTypes.shape({width:o.PropTypes.number.isRequired}).isRequired,totalWidth:o.PropTypes.number,height:o.PropTypes.number.isRequired,headerRows:o.PropTypes.array.isRequired},render:function(){var e=(this.state.resizing||this.props,n({"react-grid-Header":!0,"react-grid-Header--resizing":!!this.state.resizing})),t=this.getHeaderRows();return o.createElement("div",s({},this.props,{style:this.getStyle(),className:e}),t)},shouldComponentUpdate:function(e,t){var r=!l.sameColumns(this.props.columnMetrics.columns,e.columnMetrics.columns,l.sameColumn)||this.props.totalWidth!=e.totalWidth||this.props.headerRows.length!=e.headerRows.length||this.state.resizing!=t.resizing||this.props.sortColumn!=e.sortColumn||this.props.sortDirection!=e.sortDirection;return r},getHeaderRows:function(){var e,t=this.getColumnMetrics();this.state.resizing&&(e=this.state.resizing.column);var r=[];return this.props.headerRows.forEach(function(s,n){var i={position:"absolute",top:this.props.height*n,left:0,width:this.props.totalWidth,overflow:"hidden"};r.push(o.createElement(u,{key:s.ref,ref:s.ref,style:i,onColumnResize:this.onColumnResize,onColumnResizeEnd:this.onColumnResizeEnd,width:t.width,height:s.height||this.props.height,columns:t.columns,resizing:e,headerCellRenderer:s.headerCellRenderer,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort}))}.bind(this)),r},getInitialState:function(){return{resizing:null}},componentWillReceiveProps:function(e){this.setState({resizing:null})},onColumnResize:function(e,t){
var r=this.state.resizing||this.props,s=this.getColumnPosition(e);if(null!=s){var o={columnMetrics:i(r.columnMetrics)};o.columnMetrics=l.resizeColumn(o.columnMetrics,s,t),o.columnMetrics.totalWidth<r.columnMetrics.totalWidth&&(o.columnMetrics.totalWidth=r.columnMetrics.totalWidth),o.column=a.getColumn(o.columnMetrics.columns,s),this.setState({resizing:o})}},getColumnMetrics:function(){var e;return e=this.state.resizing?this.state.resizing.columnMetrics:this.props.columnMetrics},getColumnPosition:function(e){var t=this.getColumnMetrics(),r=-1;return t.columns.forEach(function(t,s){t.key===e.key&&(r=s)}),-1===r?null:r},onColumnResizeEnd:function(e,t){var r=this.getColumnPosition(e);null!==r&&this.props.onColumnResize&&this.props.onColumnResize(r,t||e.width)},setScrollLeft:function(e){var t=this.refs.row.getDOMNode();t.scrollLeft=e,this.refs.row.setScrollLeft(e)},getStyle:function(){return{position:"relative",height:this.props.height*this.props.headerRows.length,overflow:"hidden"}}});e.exports=c},function(e,t,r){"use strict";function s(e){return o.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var o=r(1),n=r(4),i=r(5),l=o.PropTypes,a=r(2),u=r(35),c=o.createClass({displayName:"HeaderCell",propTypes:{renderer:l.oneOfType([l.func,l.element]).isRequired,column:l.shape(a).isRequired,onResize:l.func.isRequired,height:l.number.isRequired,onResizeEnd:l.func.isRequired},render:function(){var e;this.props.column.resizable&&(e=o.createElement(u,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=n({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=n(t,this.props.className);var r=this.getCell();return o.createElement("div",{className:t,style:this.getStyle()},r,{resizeHandle:e})},getCell:function(){return o.isValidElement(this.props.renderer)?i(this.props.renderer,{column:this.props.column}):this.props.renderer({column:this.props.column})},getDefaultProps:function(){return{renderer:s}},getInitialState:function(){return{resizing:!1}},setScrollLeft:function(e){var t=this.getDOMNode();t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",overflow:"hidden",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var r=this.getWidthFromMouseEvent(e);r>0&&t(this.props.column,r)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX,r=this.getDOMNode().getBoundingClientRect().left;return t-r}});e.exports=c},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=o.PropTypes,i=r(21),l=r(32),a=r(44),u=(r(2),r(6)),c=r(41),p={overflow:o.PropTypes.string,width:n.oneOfType([n.number,n.string]),height:o.PropTypes.number,position:o.PropTypes.string},h={ASC:"ASC",DESC:"DESC",NONE:"NONE"},d=o.createClass({displayName:"HeaderRow",propTypes:{width:n.oneOfType([n.number,n.string]),height:n.number.isRequired,columns:n.oneOfType([n.array,n.object]),onColumnResize:n.func,onSort:n.func.isRequired,style:n.shape(p)},mixins:[u],render:function(){var e={width:this.props.width?this.props.width+a():"100%",height:this.props.height,whiteSpace:"nowrap",overflowX:"hidden",overflowY:"hidden"},t=this.getCells();return o.createElement("div",s({},this.props,{className:"react-grid-HeaderRow"}),o.createElement("div",{style:e},t))},getHeaderRenderer:function(e){if(e.sortable){var t=this.props.sortColumn===e.key?this.props.sortDirection:h.NONE;return o.createElement(c,{columnKey:e.key,onSort:this.props.onSort,sortDirection:t})}return this.props.headerCellRenderer||e.headerRenderer||this.props.cellRenderer},getCells:function(){for(var e=[],t=[],r=0,s=this.getSize(this.props.columns);s>r;r++){var n=this.getColumn(this.props.columns,r),i=o.createElement(l,{ref:r,key:r,height:this.props.height,column:n,renderer:this.getHeaderRenderer(n),resizing:this.props.resizing===n,onResize:this.props.onColumnResize,onResizeEnd:this.props.onColumnResizeEnd});n.locked?t.push(i):e.push(i)}return e.concat(t)},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,s){r.locked&&t.refs[s].setScrollLeft(e)})},shouldComponentUpdate:function(e){return e.width!==this.props.width||e.height!==this.props.height||e.columns!==this.props.columns||!i(e.style,this.props.style)||this.props.sortColumn!=e.sortColumn||this.props.sortDirection!=e.sortDirection},getStyle:function(){return{overflow:"hidden",width:"100%",height:this.props.height,position:"absolute"}}});e.exports=d},function(e,t,r){"use strict";var s=r(1).PropTypes;e.exports={selected:s.object.isRequired,copied:s.object,dragged:s.object,onCellClick:s.func.isRequired}},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=(r(4),r(28)),i=(r(5),o.PropTypes,o.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return o.createElement(n,s({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}}));e.exports=i},function(e,t){"use strict";var r={get:function(e,t){return"function"==typeof e.get?e.get(t):e[t]}};e.exports=r},function(e,t){"use strict";var r={appendScrollShim:function(){if(!this._scrollShim){var e=this._scrollShimSize(),t=document.createElement("div");t.classList?t.classList.add("react-grid-ScrollShim"):t.className+=" react-grid-ScrollShim",t.style.position="absolute",t.style.top=0,t.style.left=0,t.style.width=e.width+"px",t.style.height=e.height+"px",this.getDOMNode().appendChild(t),this._scrollShim=t}this._scheduleRemoveScrollShim()},_scrollShimSize:function(){return{width:this.props.width,height:this.props.length*this.props.rowHeight}},_scheduleRemoveScrollShim:function(){this._scheduleRemoveScrollShimTimer&&clearTimeout(this._scheduleRemoveScrollShimTimer),this._scheduleRemoveScrollShimTimer=setTimeout(this._removeScrollShim,200)},_removeScrollShim:function(){this._scrollShim&&(this._scrollShim.parentNode.removeChild(this._scrollShim),this._scrollShim=void 0)}};e.exports=r},function(e,t,r){"use strict";var s=r(1),o=r(25),n=s.PropTypes,i=r(39),l=s.createClass({displayName:"Viewport",mixins:[i],propTypes:{rowOffsetHeight:n.number.isRequired,totalWidth:n.number.isRequired,columnMetrics:n.object.isRequired,rowGetter:n.oneOfType([n.array,n.func]).isRequired,selectedRows:n.array,expandedRows:n.array,rowRenderer:n.func,rowsCount:n.number.isRequired,rowHeight:n.number.isRequired,onRows:n.func,onScroll:n.func,minHeight:n.number},render:function(){var e={padding:0,bottom:0,left:0,right:0,overflow:"hidden",position:"absolute",top:this.props.rowOffsetHeight};return s.createElement("div",{className:"react-grid-Viewport",style:e},s.createElement(o,{ref:"canvas",totalWidth:this.props.totalWidth,width:this.props.columnMetrics.width,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.props.columnMetrics.columns,rowRenderer:this.props.rowRenderer,visibleStart:this.state.visibleStart,visibleEnd:this.state.visibleEnd,displayStart:this.state.displayStart,displayEnd:this.state.displayEnd,cellMetaData:this.props.cellMetaData,height:this.state.height,rowHeight:this.props.rowHeight,onScroll:this.onScroll,onRows:this.props.onRows}))},getScroll:function(){return this.refs.canvas.getScroll()},onScroll:function(e){this.updateScroll(e.scrollTop,e.scrollLeft,this.state.height,this.props.rowHeight,this.props.rowsCount),this.props.onScroll&&this.props.onScroll({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft})},setScrollLeft:function(e){this.refs.canvas.setScrollLeft(e)}});e.exports=l},function(e,t,r){"use strict";var s=r(1),o=r(9),n=(r(45),s.PropTypes,Math.min),i=Math.max,l=Math.floor,a=Math.ceil;e.exports={mixins:[o.MetricsMixin],DOMMetrics:{viewportHeight:function(){return this.getDOMNode().offsetHeight}},propTypes:{rowHeight:s.PropTypes.number,rowsCount:s.PropTypes.number.isRequired},getDefaultProps:function(){return{rowHeight:30}},getInitialState:function(){return this.getGridState(this.props)},getGridState:function(e){var t=a((e.minHeight-e.rowHeight)/e.rowHeight),r=n(2*t,e.rowsCount);return{displayStart:0,displayEnd:r,height:e.minHeight,scrollTop:0,scrollLeft:0}},updateScroll:function(e,t,r,s,o){var u=a(r/s),c=l(e/s),p=n(c+u,o),h=i(0,c-2*u),d=n(c+2*u,o),f={visibleStart:c,visibleEnd:p,displayStart:h,displayEnd:d,height:r,scrollTop:e,scrollLeft:t};this.setState(f)},metricsUpdated:function(){var e=this.DOMMetrics.viewportHeight();e&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,e,this.props.rowHeight,this.props.rowsCount)},componentWillReceiveProps:function(e){this.props.rowHeight!==e.rowHeight?this.setState(this.getGridState(e)):this.props.rowsCount!==e.rowsCount&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height,e.rowHeight,e.rowsCount)}}},function(e,t,r){"use strict";var s=r(1),o=r(2),n=s.createClass({displayName:"FilterableHeaderCell",propTypes:{onChange:s.PropTypes.func.isRequired,column:s.PropTypes.shape(o).isRequired},getInitialState:function(){return{filterTerm:""}},handleChange:function(e){var t=e.target.value;this.setState({filterTerm:t}),this.props.onChange({filterTerm:t,columnKey:this.props.column.key})},componentDidUpdate:function(e){var t=this.getDOMNode();t&&t.focus()},render:function(){return s.createElement("div",null,s.createElement("div",{className:"form-group"},s.createElement(this.renderInput,null)))},renderInput:function(){return this.props.column.filterable===!1?s.createElement("span",null):s.createElement("input",{type:"text",className:"form-control input-sm",placeholder:"Search",value:this.state.filterTerm,onChange:this.handleChange})}});e.exports=n},function(e,t,r){"use strict";var s=r(1),o=(r(4),r(2),{ASC:"ASC",DESC:"DESC",NONE:"NONE"}),n=s.createClass({displayName:"SortableHeaderCell",propTypes:{columnKey:s.PropTypes.string.isRequired,onSort:s.PropTypes.func.isRequired,sortDirection:s.PropTypes.oneOf(["ASC","DESC","NONE"])},onClick:function(){var e;switch(this.props.sortDirection){case null:case void 0:case o.NONE:e=o.ASC;break;case o.ASC:e=o.DESC;break;case o.DESC:e=o.NONE}this.props.onSort(this.props.columnKey,e)},getSortByText:function(){var e={ASC:"9650",DESC:"9660",NONE:""};return String.fromCharCode(e[this.props.sortDirection])},render:function(){return s.createElement("div",{onClick:this.onClick,style:{cursor:"pointer"}},this.props.column.name,s.createElement("span",{className:"pull-right"},this.getSortByText()))}});e.exports=n},function(e,t,r){"use strict";var s=r(1),o=r(4),n=r(10),i=r(24),l=r(16),a=(r(5),s.createClass({displayName:"EditorContainer",mixins:[n],propTypes:{rowData:s.PropTypes.object.isRequired,value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired,cellMetaData:s.PropTypes.shape({selected:s.PropTypes.object.isRequired,copied:s.PropTypes.object,dragged:s.PropTypes.object,onCellClick:s.PropTypes.func,onCellDoubleClick:s.PropTypes.func}).isRequired,column:s.PropTypes.object.isRequired,height:s.PropTypes.number.isRequired},changeCommitted:!1,getInitialState:function(){return{isInvalid:!1}},componentDidMount:function(){var e=this.getInputNode();void 0!==e&&(this.setTextInputFocus(),this.getEditor().disableContainerStyles||(e.className+=" editor-main",e.style.height=this.props.height-1+"px"))},createEditor:function(){var e={ref:"editor",name:"editor",column:this.props.column,value:this.getInitialValue(),onCommit:this.commit,rowMetaData:this.getRowMetaData(),height:this.props.height,onBlur:this.commit,onOverrideKeyDown:this.onKeyDown},t=this.props.column.editor;return t&&s.isValidElement(t)?s.addons.cloneWithProps(t,e):s.createElement(i,{ref:"editor",column:this.props.column,value:this.getInitialValue(),rowMetaData:this.getRowMetaData()})},getRowMetaData:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.props.rowData,this.props.column):void 0},onPressEnter:function(e){this.commit({key:"Enter"})},onPressTab:function(e){this.commit({key:"Tab"})},onPressEscape:function(e){this.editorIsSelectOpen()?e.stopPropagation():this.props.cellMetaData.onCommitCancel()},onPressArrowDown:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowUp:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowLeft:function(e){this.isCaretAtBeginningOfInput()?this.commit(e):e.stopPropagation()},onPressArrowRight:function(e){this.isCaretAtEndOfInput()?this.commit(e):e.stopPropagation()},editorHasResults:function(){return"SELECT"===this.getEditor().getInputNode().tagName?!0:l(this.getEditor().hasResults)?this.getEditor().hasResults():!1},editorIsSelectOpen:function(){return l(this.getEditor().isSelectOpen)?this.getEditor().isSelectOpen():!1},getEditor:function(){return this.refs.editor},commit:function(e){var t=e||{},r=this.getEditor().getValue();if(this.isNewValueValid(r)){var s=this.props.column.key;this.props.cellMetaData.onCommit({cellKey:s,rowIdx:this.props.rowIdx,updated:r,key:t.key})}this.changeCommitted=!0},isNewValueValid:function(e){if(l(this.getEditor().validate)){var t=this.getEditor().validate(e);return this.setState({isInvalid:!t}),t}return!0},getInputNode:function(){return this.getEditor().getInputNode()},getInitialValue:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode;if("Delete"===t||"Backspace"===t)return"";if("Enter"===t)return this.props.value;var r=t?String.fromCharCode(t):this.props.value;return r},getContainerClass:function(){return o({"has-error":this.state.isInvalid===!0})},setCaretAtEndOfInput:function(){var e=this.getInputNode(),t=e.value.length;if(e.setSelectionRange)e.setSelectionRange(t,t);else if(e.createTextRange){var r=e.createTextRange();r.moveStart("character",t),r.collapse(),r.select()}},isCaretAtBeginningOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.selectionEnd&&0===e.selectionStart},isCaretAtEndOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.value.length},setTextInputFocus:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode,r=this.getInputNode();r.focus(),"INPUT"===r.tagName&&(this.isKeyPrintable(t)?r.select():(r.focus(),r.select()))},componentWillUnmount:function(){this.changeCommitted||this.hasEscapeBeenPressed()||this.commit({key:"Enter"})},renderStatusIcon:function(){return this.state.isInvalid===!0?s.createElement("span",{className:"glyphicon glyphicon-remove form-control-feedback"}):void 0},hasEscapeBeenPressed:function(){var e=!1,t=27;return window.event&&(window.event.keyCode===t?e=!0:window.event.which===t&&(e=!0)),e},render:function(){return s.createElement("div",{className:this.getContainerClass(),onKeyDown:this.onKeyDown},this.createEditor(),this.renderStatusIcon())}}));e.exports=a},function(e,t,r){"use strict";var s=r(3)["default"],o=r(14)["default"],n=r(1),i=(n.PropTypes,r(29)),l=(r(11),r(2),r(10)),a=r(23),u=r(40),c=r(5),p=r(9),h=r(27),d=r(36),f=r(6);o||(Object.assign=r(19));var m=n.createClass({displayName:"ReactDataGrid",propTypes:{rowHeight:n.PropTypes.number.isRequired,minHeight:n.PropTypes.number.isRequired,enableRowSelect:n.PropTypes.bool,onRowUpdated:n.PropTypes.func,rowGetter:n.PropTypes.func.isRequired,rowsCount:n.PropTypes.number.isRequired,toolbar:n.PropTypes.element,enableCellSelect:n.PropTypes.bool,columns:n.PropTypes.oneOfType([n.PropTypes.object,n.PropTypes.array]).isRequired,onFilter:n.PropTypes.func,onCellCopyPaste:n.PropTypes.func,onCellsDragged:n.PropTypes.func,onAddFilter:n.PropTypes.func},mixins:[h,p.MetricsComputatorMixin,l],getDefaultProps:function(){return{enableCellSelect:!1,tabIndex:-1,rowHeight:35,enableRowSelect:!1,minHeight:350}},getInitialState:function(){var e=this.createColumnMetrics(!0),t={columnMetrics:e,selectedRows:this.getInitialSelectedRows(),copied:null,expandedRows:[],canFilter:!1,columnFilters:{},sortDirection:null,sortColumn:null,dragged:null,scrollOffset:0};return this.props.enableCellSelect?t.selected={rowIdx:0,idx:0}:t.selected={rowIdx:-1,idx:-1},t},getInitialSelectedRows:function(){for(var e=[],t=0;t<this.props.rowsCount;t++)e.push(!1);return e},componentWillReceiveProps:function(e){e.rowsCount===this.props.rowsCount+1&&this.onAfterAddRow(e.rowsCount+1)},componentDidMount:function(){var e=0,t=this.getDOMNode().querySelector(".react-grid-Canvas");null!=t&&(e=t.offsetWidth-t.clientWidth),this.setState({scrollOffset:e})},render:function(){var e={selected:this.state.selected,dragged:this.state.dragged,onCellClick:this.onCellClick,onCellDoubleClick:this.onCellDoubleClick,onCommit:this.onCellCommit,onCommitCancel:this.setInactive,copied:this.state.copied,handleDragEnterRow:this.handleDragEnter,handleTerminateDrag:this.handleTerminateDrag},t=this.renderToolbar(),r=this.DOMMetrics.gridWidth(),o=r+this.state.scrollOffset;return n.createElement("div",{className:"react-grid-Container",style:{width:o}},t,n.createElement("div",{className:"react-grid-Main"},n.createElement(i,s({ref:"base"},this.props,{headerRows:this.getHeaderRows(),columnMetrics:this.state.columnMetrics,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,rowHeight:this.props.rowHeight,cellMetaData:e,selectedRows:this.state.selectedRows,expandedRows:this.state.expandedRows,rowOffsetHeight:this.getRowOffsetHeight(),sortColumn:this.state.sortColumn,sortDirection:this.state.sortDirection,onSort:this.handleSort,minHeight:this.props.minHeight,totalWidth:r,onViewportKeydown:this.onKeyDown,onViewportDragStart:this.onDragStart,onViewportDragEnd:this.handleDragEnd,onViewportDoubleClick:this.onViewportDoubleClick,onColumnResize:this.onColumnResize}))))},renderToolbar:function(){var e=this.props.toolbar;return n.isValidElement(e)?c(e,{onToggleFilter:this.onToggleFilter,numberOfRows:this.props.rowsCount}):void 0},onSelect:function(e){if(this.props.enableCellSelect)if(this.state.selected.rowIdx===e.rowIdx&&this.state.selected.idx===e.idx&&this.state.selected.active===!0);else{var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<f.getSize(this.state.columnMetrics.columns)&&r<this.props.rowsCount&&this.setState({selected:e})}},onCellClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx})},onCellDoubleClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx}),this.setActive("Enter")},onViewportDoubleClick:function(e){this.setActive()},onPressArrowUp:function(e){this.moveSelectedCell(e,-1,0)},onPressArrowDown:function(e){this.moveSelectedCell(e,1,0)},onPressArrowLeft:function(e){this.moveSelectedCell(e,0,-1)},onPressArrowRight:function(e){this.moveSelectedCell(e,0,1)},onPressTab:function(e){this.moveSelectedCell(e,0,e.shiftKey?-1:1)},onPressEnter:function(e){this.setActive(e.key)},onPressDelete:function(e){this.setActive(e.key)},onPressEscape:function(e){this.setInactive(e.key)},onPressBackspace:function(e){this.setActive(e.key)},onPressChar:function(e){this.isKeyPrintable(e.keyCode)&&this.setActive(e.keyCode)},onPressKeyWithCtrl:function(e){var t={KeyCode_c:99,KeyCode_C:67,KeyCode_V:86,KeyCode_v:118},r=this.state.selected.idx;if(this.canEdit(r))if(e.keyCode==t.KeyCode_c||e.keyCode==t.KeyCode_C){var s=this.getSelectedValue();this.handleCopy({value:s})}else(e.keyCode==t.KeyCode_v||e.keyCode==t.KeyCode_V)&&this.handlePaste()},onDragStart:function(e){var t=this.getSelectedValue();this.handleDragStart({idx:this.state.selected.idx,rowIdx:this.state.selected.rowIdx,value:t}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},moveSelectedCell:function(e,t,r){e.preventDefault();var s=this.state.selected.rowIdx+t,o=this.state.selected.idx+r;this.onSelect({idx:o,rowIdx:s})},getSelectedValue:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx,r=this.getColumn(this.props.columns,t).key,s=this.props.rowGetter(e);return d.get(s,r)},setActive:function(e){var t=this.state.selected.rowIdx,r=this.state.selected.idx;if(this.canEdit(r)&&!this.isActive()){var s=o(this.state.selected,{idx:r,rowIdx:t,active:!0,initialKeyCode:e});this.setState({selected:s})}},setInactive:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx;if(this.canEdit(t)&&this.isActive()){var r=o(this.state.selected,{idx:t,rowIdx:e,active:!1});this.setState({selected:r})}},canEdit:function(e){var t=this.getColumn(this.props.columns,e);return this.props.enableCellSelect===!0&&(null!=t.editor||t.editable)},isActive:function(){return this.state.selected.active===!0},onCellCommit:function(e){var t=o({},this.state.selected);t.active=!1,"Tab"===e.key&&(t.idx+=1);var r=this.state.expandedRows;this.setState({selected:t,expandedRows:r}),this.props.onRowUpdated(e)},setupGridColumns:function(){var e=this.props.columns.slice(0);if(this.props.enableRowSelect){var t={key:"select-row",name:"",formatter:n.createElement(a,null),onCellChange:this.handleRowSelect,filterable:!1,headerRenderer:n.createElement("input",{type:"checkbox",onChange:this.handleCheckboxChange}),width:60,locked:!0},r=e.unshift(t);e=r>0?e:r}return e},handleCheckboxChange:function(e){var t;t=e.currentTarget instanceof HTMLInputElement&&e.currentTarget.checked===!0?!0:!1;for(var r=[],s=0;s<this.props.rowsCount;s++)r.push(t);this.setState({selectedRows:r})},handleRowSelect:function(e,t,r){if(r.stopPropagation(),null!=this.state.selectedRows&&this.state.selectedRows.length>0){var s=this.state.selectedRows.slice();null==s[e]||0==s[e]?s[e]=!0:s[e]=!1,this.setState({selectedRows:s})}},onAfterAddRow:function(e){this.setState({selected:{idx:1,rowIdx:e-2}})},onToggleFilter:function(){this.setState({canFilter:!this.state.canFilter})},getHeaderRows:function(){var e=[{ref:"row",height:this.props.rowHeight}];return this.state.canFilter===!0&&e.push({ref:"filterRow",headerCellRenderer:n.createElement(u,{onChange:this.props.onAddFilter,column:this.props.column}),height:45}),e},getRowOffsetHeight:function(){var e=0;return this.getHeaderRows().forEach(function(t){return e+=parseFloat(t.height,10)}),e},handleSort:function(e,t){this.setState({sortDirection:t,sortColumn:e},function(){this.props.onGridSort(e,t)})},copyPasteEnabled:function(){return null!==this.props.onCellCopyPaste},handleCopy:function(e){if(this.copyPasteEnabled()){var t=e.value,r=this.state.selected,s={idx:r.idx,rowIdx:r.rowIdx};this.setState({textToCopy:t,copied:s})}},handlePaste:function(){if(this.copyPasteEnabled()){var e=this.state.selected,t=this.getColumn(this.state.columnMetrics.columns,this.state.selected.idx).key;this.props.onCellCopyPaste&&this.props.onCellCopyPaste({cellKey:t,rowIdx:e.rowIdx,value:this.state.textToCopy,fromRow:this.state.copied.rowIdx,toRow:e.rowIdx}),this.setState({copied:null})}},dragEnabled:function(){return null!==this.props.onCellsDragged},handleDragStart:function(e){if(this.dragEnabled()){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<this.getSize()&&r<this.props.rowsCount&&this.setState({dragged:e})}},handleDragEnter:function(e){if(this.dragEnabled()){var t=(this.state.selected,this.state.dragged);t.overRowIdx=e,this.setState({dragged:t})}},handleDragEnd:function(){if(this.dragEnabled()){var e,t,r=this.state.selected,s=this.state.dragged,o=this.getColumn(this.state.columnMetrics.columns,this.state.selected.idx).key;e=r.rowIdx<s.overRowIdx?r.rowIdx:s.overRowIdx,t=r.rowIdx>s.overRowIdx?r.rowIdx:s.overRowIdx,this.props.onCellsDragged&&this.props.onCellsDragged({cellKey:o,fromRow:e,toRow:t,value:s.value}),this.setState({dragged:{complete:!0}})}},handleTerminateDrag:function(){this.dragEnabled()&&this.setState({dragged:null})}});e.exports=m},function(e,t){"use strict";function r(){if(void 0===s){var e=document.createElement("div");e.style.width="50px",e.style.height="50px",e.style.overflowY="scroll",e.style.position="absolute",e.style.top="-200px",e.style.left="-200px";var t=document.createElement("div");t.style.height="100px",t.style.width="100%",e.appendChild(t),document.body.appendChild(e);var r=e.clientWidth,o=t.clientWidth;document.body.removeChild(e),s=r-o}return s}var s;e.exports=r},function(e,t){"use strict";function r(){var e=window.innerWidth,t=window.innerHeight;return e&&t||(e=document.documentElement.clientWidth,t=document.documentElement.clientHeight),e&&t||(e=document.body.clientWidth,t=document.body.clientHeight),{width:e,height:t}}e.exports=r},function(e,t,r){r(58),e.exports=r(18).Object.assign},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){var r={}.toString;e.exports=function(e){return r.call(e).slice(8,-1)}},function(e,t,r){var s=r(47);e.exports=function(e,t,r){if(s(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,s){return e.call(t,r,s)};case 3:return function(r,s,o){return e.call(t,r,s,o)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,r){var s=r(53),o=r(18),n=r(49),i="prototype",l=function(e,t,r){var a,u,c,p=e&l.F,h=e&l.G,d=e&l.S,f=e&l.P,m=e&l.B,g=e&l.W,w=h?o:o[t]||(o[t]={}),y=h?s:d?s[t]:(s[t]||{})[i];h&&(r=t);for(a in r)u=!p&&y&&a in y,u&&a in w||(c=u?y[a]:r[a],w[a]=h&&"function"!=typeof y[a]?r[a]:m&&u?n(c,s):g&&y[a]==c?function(e){var t=function(t){return this instanceof e?new e(t):e(t)};return t[i]=e[i],t}(c):f&&"function"==typeof c?n(Function.call,c):c,f&&((w[i]||(w[i]={}))[a]=c))};l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,e.exports=l},function(e,t){e.exports=function(e){try{return!!e()}catch(t){return!0}}},function(e,t){var r=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(e,t,r){var s=r(48);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==s(e)?e.split(""):Object(e)}},function(e,t){var r=Object;e.exports={create:r.create,getProto:r.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:r.getOwnPropertyDescriptor,setDesc:r.defineProperty,setDescs:r.defineProperties,getKeys:r.keys,getNames:r.getOwnPropertyNames,getSymbols:r.getOwnPropertySymbols,each:[].forEach}},function(e,t,r){var s=r(55),o=r(57),n=r(54);e.exports=r(52)(function(){var e=Object.assign,t={},r={},s=Symbol(),o="abcdefghijklmnopqrst";return t[s]=7,o.split("").forEach(function(e){r[e]=e}),7!=e({},t)[s]||Object.keys(e({},r)).join("")!=o})?function(e,t){for(var r=o(e),i=arguments,l=i.length,a=1,u=s.getKeys,c=s.getSymbols,p=s.isEnum;l>a;)for(var h,d=n(i[a++]),f=c?u(d).concat(c(d)):u(d),m=f.length,g=0;m>g;)p.call(d,h=f[g++])&&(r[h]=d[h]);return r}:Object.assign},function(e,t,r){var s=r(50);e.exports=function(e){return Object(s(e))}},function(e,t,r){var s=r(51);s(s.S+s.F,"Object",{assign:r(56)})},function(e,t,r){"use strict";var s=r(20),o={current:{},withContext:function(e,t){var r,n=o.current;o.current=s({},n,e);try{r=t()}finally{o.current=n}return r}};e.exports=o},function(e,t){"use strict";var r={current:null};e.exports=r},function(e,t,r){(function(t){"use strict";function s(e,r){Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[r]:null},set:function(e){"production"!==t.env.NODE_ENV?l(!1,"Don't set the "+r+" property of the component. Mutate the existing props object instead."):null,this._store[r]=e}})}function o(e){try{var t={props:!0};for(var r in t)s(e,r);u=!0}catch(o){}}var n=r(59),i=r(60),l=r(15),a={key:!0,ref:!0},u=!1,c=function(e,r,s,o,n,i){return this.type=e,this.key=r,this.ref=s,this._owner=o,this._context=n,"production"!==t.env.NODE_ENV&&(this._store={validated:!1,props:i},u)?void Object.freeze(this):void(this.props=i)};c.prototype={_isReactElement:!0},"production"!==t.env.NODE_ENV&&o(c.prototype),c.createElement=function(e,r,s){var o,u={},p=null,h=null;if(null!=r){h=void 0===r.ref?null:r.ref,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(null!==r.key,"createElement(...): Encountered component with a `key` of null. In a future version, this will be treated as equivalent to the string 'null'; instead, provide an explicit key or use undefined."):null),p=null==r.key?null:""+r.key;for(o in r)r.hasOwnProperty(o)&&!a.hasOwnProperty(o)&&(u[o]=r[o])}var d=arguments.length-2;if(1===d)u.children=s;else if(d>1){for(var f=Array(d),m=0;d>m;m++)f[m]=arguments[m+2];u.children=f}if(e&&e.defaultProps){var g=e.defaultProps;for(o in g)"undefined"==typeof u[o]&&(u[o]=g[o])}return new c(e,p,h,i.current,n.current,u)},c.createFactory=function(e){var t=c.createElement.bind(null,e);return t.type=e,t},c.cloneAndReplaceProps=function(e,r){var s=new c(e.type,e.key,e.ref,e._owner,e._context,r);return"production"!==t.env.NODE_ENV&&(s._store.validated=e._store.validated),s},c.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},e.exports=c}).call(t,r(8))},function(e,t,r){(function(t){"use strict";function s(e){return function(t,r,s){t.hasOwnProperty(r)?t[r]=e(t[r],s):t[r]=s}}function o(e,t){for(var r in t)if(t.hasOwnProperty(r)){var s=h[r];s&&h.hasOwnProperty(r)?s(e,r,t[r]):e.hasOwnProperty(r)||(e[r]=t[r])}return e}var n=r(20),i=r(7),l=r(63),a=r(64),u=r(15),c=!1,p=s(function(e,t){return n({},t,e)}),h={children:i,className:s(a),style:p},d={TransferStrategies:h,mergeProps:function(e,t){return o(n({},e),t)},Mixin:{transferPropsTo:function(e){return"production"!==t.env.NODE_ENV?l(e._owner===this,"%s: You can't call transferPropsTo() on a component that you don't own, %s. This usually means you are calling transferPropsTo() on a component passed in as props or children.",this.constructor.displayName,"string"==typeof e.type?e.type:e.type.displayName):l(e._owner===this),"production"!==t.env.NODE_ENV&&(c||(c=!0,"production"!==t.env.NODE_ENV?u(!1,"transferPropsTo is deprecated. See http://fb.me/react-transferpropsto for more information."):null)),o(e.props,this.props),e}}};e.exports=d}).call(t,r(8))},function(e,t,r){(function(t){"use strict";var r=function(e,r,s,o,n,i,l,a){if("production"!==t.env.NODE_ENV&&void 0===r)throw new Error("invariant requires an error message argument");if(!e){var u;if(void 0===r)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[s,o,n,i,l,a],p=0;u=new Error("Invariant Violation: "+r.replace(/%s/g,function(){return c[p++]}))}throw u.framesToPop=1,u}};e.exports=r}).call(t,r(8))},function(e,t){"use strict";function r(e){e||(e="");var t,r=arguments.length;if(r>1)for(var s=1;r>s;s++)t=arguments[s],t&&(e=(e?e+" ":"")+t);return e}e.exports=r},function(e,t){var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=r},function(e,t,r){"use strict";var s=r(1),o=r(73),n=(r(10),r(2)),i=s.PropTypes.shape({id:s.PropTypes.required,title:s.PropTypes.string}),l=s.createClass({displayName:"AutoCompleteEditor",propTypes:{onCommit:s.PropTypes.func.isRequired,options:s.PropTypes.arrayOf(i).isRequired,label:s.PropTypes.any,value:s.PropTypes.any.isRequired,valueParams:s.PropTypes.arrayOf(s.PropTypes.string),column:s.PropTypes.shape(n).isRequired,resultIdentifier:s.PropTypes.string,search:s.PropTypes.string,height:s.PropTypes.string,onKeyDown:s.PropTypes.func.isRequired},getDefaultProps:function(){return{label:"title",resultIdentifier:"id"}},getValue:function(){var e,t={};return this.hasResults()&&this.isFocusedOnSuggestion()?(e=this.getLabel(this.refs.autoComplete.state.focusedValue),this.props.valueParams&&(e=this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue,this.props.valueParams))):e=this.refs.autoComplete.state.searchTerm,t[this.props.column.key]=e,
t},getInputNode:function(){return this.getDOMNode().getElementsByTagName("input")[0]},render:function(){return s.createElement("div",{height:this.props.height,onKeyDown:this.props.onKeyDown},s.createElement(o,{search:this.props.search,ref:"autoComplete",label:this.props.label,onChange:this.handleChange,resultIdentifier:this.props.resultIdentifier,options:this.props.options,value:{title:this.props.value}}))},handleChange:function(){this.props.onCommit()},hasResults:function(){return this.refs.autoComplete.state.results.length>0},isFocusedOnSuggestion:function(){var e=this.refs.autoComplete;return null!=e.state.focusedValue},getLabel:function(e){var t=this.props.label;return"function"==typeof t?t(e):"string"==typeof t?e[t]:void 0},constuctValueFromParams:function(e,t){if(!t)return"";for(var r=[],s=0,o=t.length;o>s;s++)r.push(e[t[s]]);return r.join("|")}});e.exports=l},function(e,t,r){"use strict";var s=r(3)["default"],o=r(1),n=r(66),i=o.createClass({displayName:"AutoCompleteAsyncEditor",propTypes:{cacheResults:o.PropTypes.bool,column:o.PropTypes.object,rowMetaData:o.PropTypes.object,height:o.PropTypes.string,label:o.PropTypes.string,onCommit:o.PropTypes.func,onKeyDown:o.PropTypes.func,resultIdentifier:o.PropTypes.string,searchSourceArgs:o.PropTypes.array,searchUrl:o.PropTypes.func,value:o.PropTypes.string,valueParams:o.PropTypes.arrayOf(o.PropTypes.string)},getDefaultProps:function(){return{label:"title"}},getSearchParams:function(){var e=this.props.rowMetaData,t=this.props.searchSourceArgs.map(function(t){if(null==e[t])throw"Cannot find Search Source Paramater "+t+" in rowMetaData. You must add an entry for this in models/GridColumn.js";return e[t]});return t},getInputNode:function(){return this.getDOMNode().getElementsByTagName("input")[0]},getValue:function(){return this.refs.autocomplete.getValue()},hasResults:function(){return this.refs.autocomplete.hasResults()},_searchRemote:function(e,t,r){var s=this.getSearchParams();s.push(this._onXHRSuccess.bind(null,r,t)),this.props.searchUrl.apply(this,s)},_onXHRSuccess:function(e,t,r,s,o){e(null,this._filterData(r,t))},_onXHRError:function(e,t,r,s){e(s)},_filterData:function(e,t){for(var r=new RegExp(t,"i"),s=[],o=0,n=e.length;n>o;o++)r.exec(e[o][this.props.label])&&s.push(e[o]);return s.slice(0,100)},render:function(){var e,t=this.props.column.formatter;return e="function"==typeof t&&"function"==typeof t.format?t.format(this.props.value):this.props.value,o.createElement(n,s({ref:"autocomplete"},this.props,{options:[],search:this._searchRemote,value:e}))}});e.exports=i},function(e,t,r){"use strict";var s=r(1),o=r(2),n=s.createClass({displayName:"DropDownEditor",propTypes:{options:s.PropTypes.arrayOf(s.PropTypes.string).isRequired,value:s.PropTypes.string.isRequired,onCommit:s.PropTypes.func.isRequired,column:s.PropTypes.shape(o).isRequired},getStyle:function(){return{width:"100%"}},render:function(){return s.createElement("select",{ref:"select",style:this.getStyle(),defaultValue:this.props.value,onChange:this.onChange,onClick:this.onClick,onDoubleClick:this.onDoubleClick},this.renderOptions())},renderOptions:function(){var e=[];return this.props.options.forEach(function(t){e.push(s.createElement("option",{key:t,value:t},t))},this),e},getValue:function(){var e={};return e[this.props.column.key]=this.refs.select.getDOMNode().value,e},getInputNode:function(){return this.refs.select.getDOMNode()},onChange:function(){this.props.onCommit({key:"Enter"})},onClick:function(e){this.getInputNode().focus()},onDoubleClick:function(e){this.getInputNode().focus()}});e.exports=n},function(e,t,r){"use strict";var s={AutoComplete:r(66),DropDownEditor:r(68),SimpleTextEditor:r(24),AutoCompleteAsync:r(67),CheckboxEditor:r(23)};e.exports=s},function(e,t,r){"use strict";var s=r(1),o={},n={},i=s.createClass({displayName:"ImageFormatter",propTypes:{value:s.PropTypes.string.isRequired},getInitialState:function(){return{ready:!1}},componentWillMount:function(){this._load(this.props.value)},componentWillReceiveProps:function(e){e.value!==this.props.value&&(this.setState({value:null}),this._load(e.value))},render:function(){var e=this.state.value?{backgroundImage:"url("+this.state.value+")"}:void 0;return s.createElement("div",{className:"react-grid-image",style:e})},_load:function(e){if(n[e])return void this.setState({value:e});if(o[e])return void o[e].push(this._onLoad);o[e]=[this._onLoad];var t=new Image;t.onload=function(){o[e].forEach(function(t){t(e)}),delete o[e],t.onload=null,e=void 0},t.src=e},_onLoad:function(e){this.isMounted()&&e===this.props.value&&this.setState({value:e})}});e.exports=i},function(e,t,r){"use strict";var s=r(70),o={ImageFormatter:s};e.exports=o},function(e,t,r){"use strict";var s=r(1),o=(r(11),s.createClass({displayName:"Toolbar",propTypes:{onAddRow:s.PropTypes.func,onToggleFilter:s.PropTypes.func.isRequired,enableFilter:s.PropTypes.bool,numberOfRows:s.PropTypes.number.isRequired},onAddRow:function(){null!==this.props.onAddRow&&this.props.onAddRow instanceof Function&&this.props.onAddRow({newRowIndex:this.props.numberOfRows})},getDefaultProps:function(){return{enableAddRow:!0}},renderAddRowButton:function(){return this.props.onAddRow?s.createElement("button",{type:"button",className:"btn",onClick:this.onAddRow},"Add Row"):void 0},renderToggleFilterButton:function(){return this.props.enableFilter?s.createElement("button",{type:"button",className:"btn",onClick:this.props.onToggleFilter},"Filter Rows"):void 0},render:function(){return s.createElement("div",{className:"react-grid-Toolbar"},s.createElement("div",{className:"tools"},this.renderAddRowButton(),this.renderToggleFilterButton()))}}));e.exports=o},function(e,t,r){!function(t,s){e.exports=s(r(1))}(this,function(e){return function(e){function t(s){if(r[s])return r[s].exports;var o=r[s]={exports:{},id:s,loaded:!1};return e[s].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function s(e,t,r){if(!e)return r(null,[]);t=new RegExp(t,"i");for(var s=[],o=0,n=e.length;n>o;o++)t.exec(e[o].title)&&s.push(e[o]);r(null,s)}var o=r(1),n=r(2),i=o.createClass({displayName:"Autocomplete",propTypes:{options:o.PropTypes.any,search:o.PropTypes.func,resultRenderer:o.PropTypes.oneOfType([o.PropTypes.component,o.PropTypes.func]),value:o.PropTypes.object,onChange:o.PropTypes.func,onError:o.PropTypes.func},getDefaultProps:function(){return{search:s}},getInitialState:function(){var e=this.props.searchTerm?this.props.searchTerm:this.props.value?this.props.value.title:"";return{results:[],showResults:!1,showResultsInProgress:!1,searchTerm:e,focusedValue:null}},getResultIdentifier:function(e){return void 0===this.props.resultIdentifier?e.id:e[this.props.resultIdentifier]},render:function(){var e=n(this.props.className,"react-autocomplete-Autocomplete",this.state.showResults?"react-autocomplete-Autocomplete--resultsShown":void 0),t={position:"relative",outline:"none"};return o.createElement("div",{tabIndex:"1",className:e,onFocus:this.onFocus,onBlur:this.onBlur,style:t},o.createElement("input",{ref:"search",className:"react-autocomplete-Autocomplete__search",style:{width:"100%"},onClick:this.showAllResults,onChange:this.onQueryChange,onFocus:this.showAllResults,onBlur:this.onQueryBlur,onKeyDown:this.onQueryKeyDown,value:this.state.searchTerm}),o.createElement(l,{className:"react-autocomplete-Autocomplete__results",onSelect:this.onValueChange,onFocus:this.onValueFocus,results:this.state.results,focusedValue:this.state.focusedValue,show:this.state.showResults,renderer:this.props.resultRenderer,label:this.props.label,resultIdentifier:this.props.resultIdentifier}))},componentWillReceiveProps:function(e){var t=e.searchTerm?e.searchTerm:e.value?e.value.title:"";this.setState({searchTerm:t})},componentWillMount:function(){this.blurTimer=null},showResults:function(e){this.setState({showResultsInProgress:!0}),this.props.search(this.props.options,e.trim(),this.onSearchComplete)},showAllResults:function(){this.state.showResultsInProgress||this.state.showResults||this.showResults("")},onValueChange:function(e){var t={value:e,showResults:!1};e&&(t.searchTerm=e.title),this.setState(t),this.props.onChange&&this.props.onChange(e)},onSearchComplete:function(e,t){if(e){if(!this.props.onError)throw e;this.props.onError(e)}this.setState({showResultsInProgress:!1,showResults:!0,results:t})},onValueFocus:function(e){this.setState({focusedValue:e})},onQueryChange:function(e){var t=e.target.value;this.setState({searchTerm:t,focusedValue:null}),this.showResults(t)},onFocus:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null),this.refs.search.getDOMNode().focus()},onBlur:function(){this.blurTimer=setTimeout(function(){this.isMounted()&&this.setState({showResults:!1})}.bind(this),100)},onQueryKeyDown:function(e){if("Enter"===e.key)e.preventDefault(),this.state.focusedValue&&this.onValueChange(this.state.focusedValue);else if("ArrowUp"===e.key&&this.state.showResults){e.preventDefault();var t=Math.max(this.focusedValueIndex()-1,0);this.setState({focusedValue:this.state.results[t]})}else if("ArrowDown"===e.key)if(e.preventDefault(),this.state.showResults){var r=Math.min(this.focusedValueIndex()+(this.state.showResults?1:0),this.state.results.length-1);this.setState({showResults:!0,focusedValue:this.state.results[r]})}else this.showAllResults()},focusedValueIndex:function(){if(!this.state.focusedValue)return-1;for(var e=0,t=this.state.results.length;t>e;e++)if(this.getResultIdentifier(this.state.results[e])===this.getResultIdentifier(this.state.focusedValue))return e;return-1}}),l=o.createClass({displayName:"Results",getResultIdentifier:function(e){if(void 0===this.props.resultIdentifier){if(!e.id)throw"id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component";return e.id}return e[this.props.resultIdentifier]},render:function(){var e={display:this.props.show?"block":"none",position:"absolute",listStyleType:"none"},t=this.props,r=t.className,s=function(e,t){var r={},s=Object.prototype.hasOwnProperty;if(null==e)throw new TypeError;for(var o in e)s.call(e,o)&&!s.call(t,o)&&(r[o]=e[o]);return r}(t,{className:1});return o.createElement("ul",o.__spread({},s,{style:e,className:r+" react-autocomplete-Results"}),this.props.results.map(this.renderResult))},renderResult:function(e){var t=this.props.focusedValue&&this.getResultIdentifier(this.props.focusedValue)===this.getResultIdentifier(e),r=this.props.renderer||a;return r({ref:t?"focused":void 0,key:this.getResultIdentifier(e),result:e,focused:t,onMouseEnter:this.onMouseEnterResult,onClick:this.props.onSelect,label:this.props.label})},componentDidUpdate:function(){this.scrollToFocused()},componentDidMount:function(){this.scrollToFocused()},componentWillMount:function(){this.ignoreFocus=!1},scrollToFocused:function(){var e=this.refs&&this.refs.focused;if(e){var t=this.getDOMNode(),r=t.scrollTop,s=t.offsetHeight,o=e.getDOMNode(),n=o.offsetTop,i=n+o.offsetHeight;r>n?(this.ignoreFocus=!0,t.scrollTop=n):i-r>s&&(this.ignoreFocus=!0,t.scrollTop=i-s)}},onMouseEnterResult:function(e,t){if(this.ignoreFocus)this.ignoreFocus=!1;else{var r=this.getDOMNode(),s=r.scrollTop,o=r.offsetHeight,n=e.target,i=n.offsetTop,l=i+n.offsetHeight;l>s&&s+o>i&&this.props.onFocus(t)}}}),a=o.createClass({displayName:"Result",getDefaultProps:function(){return{label:function(e){return e.title}}},getLabel:function(e){return"function"==typeof this.props.label?this.props.label(e):"string"==typeof this.props.label?e[this.props.label]:void 0},render:function(){var e=n({"react-autocomplete-Result":!0,"react-autocomplete-Result--active":this.props.focused});return o.createElement("li",{style:{listStyleType:"none"},className:e,onClick:this.onClick,onMouseEnter:this.onMouseEnter},o.createElement("a",null,this.getLabel(this.props.result)))},onClick:function(){this.props.onClick(this.props.result)},onMouseEnter:function(e){this.props.onMouseEnter&&this.props.onMouseEnter(e,this.props.result)},shouldComponentUpdate:function(e){return e.result.id!==this.props.result.id||e.focused!==this.props.focused}});e.exports=i},function(t,r){t.exports=e},function(e,t,r){function s(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+s.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}var o,n;"undefined"!=typeof e&&e.exports&&(e.exports=s),o=[],n=function(){return s}.apply(t,o),!(void 0!==n&&(e.exports=n))}])})}])}); |
frontend/App/index.js | shoumma/ReForum | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import { Provider } from 'react-redux';
import styles from './styles';
// app store
import appStore from './store';
// app views
import AppContainer from './App';
import AdminContainer from './Admin';
import Dashboard from '../Views/AdminDashboard';
import Header from 'Containers/Header';
import ForumFeed from '../Views/ForumFeed';
import SingleDiscussion from '../Views/SingleDiscussion';
import NewDiscussion from '../Views/NewDiscussion';
import UserProfile from '../Views/UserProfile';
import NotFound from '../Views/NotFound';
ReactDOM.render (
<Provider store={appStore}>
<Router history={browserHistory}>
<Route path="/admin" component={AdminContainer}>
<IndexRoute component={Dashboard} />
</Route>
<Route path="/" component={AppContainer}>
<IndexRoute component={ForumFeed} />
<Route path=":forum" component={ForumFeed} />
<Route path=":forum/discussion/:discussion" component={SingleDiscussion} />
<Route path=":forum/new_discussion" component={NewDiscussion} />
<Route path="user/:username" component={UserProfile} />
<Route path="*" component={NotFound} />
</Route>
</Router>
</Provider>,
document.getElementById('root')
);
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Base/Loading/Loading.js | sambaheerathan/carbon-apimgt | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react'
import PropTypes from 'prop-types'
import {Spin, Row, Col} from 'antd'
const LoadingAnimation = (props) => {
return (
<Row type="flex" justify="center" align="middle">
<Col span={24} style={{textAlign: "center"}}>
<Spin spinning={true} size="large"/>
</Col>
</Row>
);
};
LoadingAnimation.propTypes = {
message: PropTypes.string
};
LoadingAnimation.defaultProps = {
message: "Loading . . ."
};
export default LoadingAnimation |
test/NavItemSpec.js | pieter-lazzaro/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import NavItem from '../src/NavItem';
describe('NavItem', function () {
it('Should add active class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem active={true}>
Item content
</NavItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'active'));
});
it('Should add disabled class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem disabled={true}>
Item content
</NavItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled'));
});
it('Should add DOM properties', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/some/unique-thing/" title="content">
Item content
</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.ok(linkElement.href.indexOf('/some/unique-thing/') >= 0);
assert.equal(linkElement.title, 'content');
});
it('Should not add anchor properties to li', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href='/hi' title='boom!'>
Item content
</NavItem>
);
assert.ok(!React.findDOMNode(instance).hasAttribute('href'));
assert.ok(!React.findDOMNode(instance).hasAttribute('title'));
});
it('Should call `onSelect` when item is selected', function (done) {
function handleSelect(key) {
assert.equal(key, '2');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<NavItem eventKey='2' onSelect={handleSelect}>
<span>Item content</span>
</NavItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
});
it('Should not call `onSelect` when item disabled and is selected', function () {
function handleSelect() {
throw new Error('onSelect should not be called');
}
let instance = ReactTestUtils.renderIntoDocument(
<NavItem disabled={true} onSelect={handleSelect}>
<span>Item content</span>
</NavItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
});
it('Should set target attribute on anchor', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/some/unique-thing/" target="_blank">Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.target, '_blank');
});
it('Should call `onSelect` with target attribute', function (done) {
function handleSelect(key, href, target) {
assert.equal(target, '_blank');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<NavItem onSelect={handleSelect} target="_blank">
<span>Item content</span>
</NavItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
});
it('Should set role="button" when href=="#"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="#" target="_blank">Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert(linkElement.outerHTML.match('role="button"'), true);
});
it('Should not set role when href!="#"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/path/to/stuff" target="_blank">Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.outerHTML.match('role="button"'), null);
});
describe('Web Accessibility', function(){
it('Should pass aria-controls to the link', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/path/to/stuff" target="_blank" aria-controls='hi'>Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.ok(linkElement.hasAttribute('aria-controls'));
});
it('Should add aria-selected to the link', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem active>Item content</NavItem>
);
let linkElement = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.getAttribute('aria-selected'), 'true');
});
it('Should pass role down', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem role='tab'>Item content</NavItem>
);
let linkElement = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.getAttribute('role'), 'tab');
});
});
});
|
src/internal/SlideIn.js | skarnecki/material-ui | import React from 'react';
import ReactTransitionGroup from 'react-addons-transition-group';
import SlideInChild from './SlideInChild';
class SlideIn extends React.Component {
static propTypes = {
childStyle: React.PropTypes.object,
children: React.PropTypes.node,
direction: React.PropTypes.oneOf(['left', 'right', 'up', 'down']),
enterDelay: React.PropTypes.number,
style: React.PropTypes.object,
};
static defaultProps = {
enterDelay: 0,
direction: 'left',
};
static contextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
getLeaveDirection = () => {
return this.props.direction;
};
render() {
const {
enterDelay,
children,
childStyle,
direction,
style,
...other,
} = this.props;
const {prepareStyles} = this.context.muiTheme;
const mergedRootStyles = Object.assign({}, {
position: 'relative',
overflow: 'hidden',
height: '100%',
}, style);
const newChildren = React.Children.map(children, (child) => {
return (
<SlideInChild
key={child.key}
direction={direction}
enterDelay={enterDelay}
getLeaveDirection={this.getLeaveDirection}
style={childStyle}
>
{child}
</SlideInChild>
);
}, this);
return (
<ReactTransitionGroup
{...other}
style={prepareStyles(mergedRootStyles)}
component="div"
>
{newChildren}
</ReactTransitionGroup>
);
}
}
export default SlideIn;
|
client/src/views/IndexPage.js | MissUchiha/CANX | import React from 'react'
import {Link} from 'react-router'
import Logo from './Logo'
function IndexPage(props) {
return (
<div className="index">
<Logo/>
<h1 className="title"> CANX</h1>
<Link to='/login'> <div className="indeks-btn"> LOGIN </div> </Link>
<Link to='/register'><div className="indeks-btn"> REGISTER </div></Link>
</div>
)
}
export default IndexPage
|
src/Composite/InputAreaWithLabelComposite/InputAreaWithLabelComposite.spec.js | skyiea/wix-style-react | import React from 'react';
import InputAreaWithLabelComposite from './InputAreaWithLabelComposite';
import Label from '../../Label';
import Input from '../../Input';
import InputArea from '../../InputArea';
import AutoComplete from '../../AutoComplete';
import textAreaDriverFactory from '../../TextArea/TextArea.driver';
import textFieldDriverFactory from '../../TextField/TextField.driver';
import autoCompleteCompositeDriverFactory from '../../AutoCompleteComposite/AutoCompleteComposite.driver';
import {createDriverFactory} from '../../test-common';
describe('InputAreaWithLabelComposite', () => {
const createTextAreaDriver = createDriverFactory(textAreaDriverFactory);
const createTextFieldDriver = createDriverFactory(textFieldDriverFactory);
const createAutoCompleteDriver = createDriverFactory(autoCompleteCompositeDriverFactory);
it('should remove label wrapping when label not given', () => {
const driver = createTextFieldDriver(<InputAreaWithLabelComposite><Input/></InputAreaWithLabelComposite>);
expect(driver.hasLabel()).toBe(false);
expect(driver.getNumberOfChildren()).toBe(1);
});
it('should render Label with Input', () => {
const driver = createTextFieldDriver(<InputAreaWithLabelComposite><Label>myLabel</Label><Input/></InputAreaWithLabelComposite>);
expect(driver.hasLabel()).toBe(true);
expect(driver.getLabel()).toBe('myLabel');
expect(driver.hasInput()).toBe(true);
});
it('should render Label with InputArea', () => {
const driver = createTextAreaDriver(<InputAreaWithLabelComposite><Label/><InputArea/></InputAreaWithLabelComposite>);
expect(driver.hasLabel()).toBe(true);
expect(driver.hasInputArea()).toBe(true);
});
it('should render Label with AutoComplete', () => {
const driver = createAutoCompleteDriver(<InputAreaWithLabelComposite><Label/><AutoComplete/></InputAreaWithLabelComposite>);
expect(driver.hasLabel()).toBe(true);
expect(driver.hasAutoComplete()).toBe(true);
});
describe('label attributes', () => {
it('should FieldLabelAttributes not exists if all attributes empty or false', () => {
const driver = createAutoCompleteDriver(<InputAreaWithLabelComposite><Label>label</Label><InputArea/></InputAreaWithLabelComposite>);
expect(driver.hasFieldLabelAttributes()).toBe(false);
});
it('should FieldLabelAttributes exists if required', () => {
const driver = createAutoCompleteDriver(<InputAreaWithLabelComposite required><Label>label</Label><InputArea/></InputAreaWithLabelComposite>);
expect(driver.hasFieldLabelAttributes()).toBe(true);
});
it('should FieldLabelAttributes exists if required and with one child', () => {
const driver = createAutoCompleteDriver(<InputAreaWithLabelComposite required><InputArea/></InputAreaWithLabelComposite>);
expect(driver.hasFieldLabelAttributes()).toBe(true);
});
it('should FieldLabelAttributes exists if info', () => {
const driver = createAutoCompleteDriver(<InputAreaWithLabelComposite info="info"><Label>label</Label><InputArea/></InputAreaWithLabelComposite>);
expect(driver.hasFieldLabelAttributes()).toBe(true);
});
it('should FieldLabelAttributes exists if info and with one child', () => {
const driver = createAutoCompleteDriver(<InputAreaWithLabelComposite info="info"><InputArea/></InputAreaWithLabelComposite>);
expect(driver.hasFieldLabelAttributes()).toBe(true);
});
});
});
|
node_modules/jade/node_modules/with/node_modules/acorn-globals/node_modules/acorn/test/compare/traceur.js | smendou/mirouf | (function(global) {
'use strict';
if (global.$traceurRuntime) {
return;
}
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $Object.defineProperties;
var $defineProperty = $Object.defineProperty;
var $freeze = $Object.freeze;
var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $Object.getOwnPropertyNames;
var $keys = $Object.keys;
var $hasOwnProperty = $Object.prototype.hasOwnProperty;
var $toString = $Object.prototype.toString;
var $preventExtensions = Object.preventExtensions;
var $seal = Object.seal;
var $isExtensible = Object.isExtensible;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var types = {
void: function voidType() {},
any: function any() {},
string: function string() {},
number: function number() {},
boolean: function boolean() {}
};
var method = nonEnum;
var counter = 0;
function newUniqueString() {
return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';
}
var symbolInternalProperty = newUniqueString();
var symbolDescriptionProperty = newUniqueString();
var symbolDataProperty = newUniqueString();
var symbolValues = $create(null);
var privateNames = $create(null);
function createPrivateName() {
var s = newUniqueString();
privateNames[s] = true;
return s;
}
function isSymbol(symbol) {
return typeof symbol === 'object' && symbol instanceof SymbolValue;
}
function typeOf(v) {
if (isSymbol(v))
return 'symbol';
return typeof v;
}
function Symbol(description) {
var value = new SymbolValue(description);
if (!(this instanceof Symbol))
return value;
throw new TypeError('Symbol cannot be new\'ed');
}
$defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(Symbol.prototype, 'toString', method(function() {
var symbolValue = this[symbolDataProperty];
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
var desc = symbolValue[symbolDescriptionProperty];
if (desc === undefined)
desc = '';
return 'Symbol(' + desc + ')';
}));
$defineProperty(Symbol.prototype, 'valueOf', method(function() {
var symbolValue = this[symbolDataProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
return symbolValue;
}));
function SymbolValue(description) {
var key = newUniqueString();
$defineProperty(this, symbolDataProperty, {value: this});
$defineProperty(this, symbolInternalProperty, {value: key});
$defineProperty(this, symbolDescriptionProperty, {value: description});
freeze(this);
symbolValues[key] = this;
}
$defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(SymbolValue.prototype, 'toString', {
value: Symbol.prototype.toString,
enumerable: false
});
$defineProperty(SymbolValue.prototype, 'valueOf', {
value: Symbol.prototype.valueOf,
enumerable: false
});
var hashProperty = createPrivateName();
var hashPropertyDescriptor = {value: undefined};
var hashObjectProperties = {
hash: {value: undefined},
self: {value: undefined}
};
var hashCounter = 0;
function getOwnHashObject(object) {
var hashObject = object[hashProperty];
if (hashObject && hashObject.self === object)
return hashObject;
if ($isExtensible(object)) {
hashObjectProperties.hash.value = hashCounter++;
hashObjectProperties.self.value = object;
hashPropertyDescriptor.value = $create(null, hashObjectProperties);
$defineProperty(object, hashProperty, hashPropertyDescriptor);
return hashPropertyDescriptor.value;
}
return undefined;
}
function freeze(object) {
getOwnHashObject(object);
return $freeze.apply(this, arguments);
}
function preventExtensions(object) {
getOwnHashObject(object);
return $preventExtensions.apply(this, arguments);
}
function seal(object) {
getOwnHashObject(object);
return $seal.apply(this, arguments);
}
Symbol.iterator = Symbol();
freeze(SymbolValue.prototype);
function toProperty(name) {
if (isSymbol(name))
return name[symbolInternalProperty];
return name;
}
function getOwnPropertyNames(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (!symbolValues[name] && !privateNames[name])
rv.push(name);
}
return rv;
}
function getOwnPropertyDescriptor(object, name) {
return $getOwnPropertyDescriptor(object, toProperty(name));
}
function getOwnPropertySymbols(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var symbol = symbolValues[names[i]];
if (symbol)
rv.push(symbol);
}
return rv;
}
function hasOwnProperty(name) {
return $hasOwnProperty.call(this, toProperty(name));
}
function getOption(name) {
return global.traceur && global.traceur.options[name];
}
function setProperty(object, name, value) {
var sym,
desc;
if (isSymbol(name)) {
sym = name;
name = name[symbolInternalProperty];
}
object[name] = value;
if (sym && (desc = $getOwnPropertyDescriptor(object, name)))
$defineProperty(object, name, {enumerable: false});
return value;
}
function defineProperty(object, name, descriptor) {
if (isSymbol(name)) {
if (descriptor.enumerable) {
descriptor = $create(descriptor, {enumerable: {value: false}});
}
name = name[symbolInternalProperty];
}
$defineProperty(object, name, descriptor);
return object;
}
function polyfillObject(Object) {
$defineProperty(Object, 'defineProperty', {value: defineProperty});
$defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});
$defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});
$defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});
$defineProperty(Object, 'freeze', {value: freeze});
$defineProperty(Object, 'preventExtensions', {value: preventExtensions});
$defineProperty(Object, 'seal', {value: seal});
Object.getOwnPropertySymbols = getOwnPropertySymbols;
}
function exportStar(object) {
for (var i = 1; i < arguments.length; i++) {
var names = $getOwnPropertyNames(arguments[i]);
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (privateNames[name])
continue;
(function(mod, name) {
$defineProperty(object, name, {
get: function() {
return mod[name];
},
enumerable: true
});
})(arguments[i], names[j]);
}
}
return object;
}
function isObject(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
function toObject(x) {
if (x == null)
throw $TypeError();
return $Object(x);
}
function assertObject(x) {
if (!isObject(x))
throw $TypeError(x + ' is not an Object');
return x;
}
function setupGlobals(global) {
global.Symbol = Symbol;
global.Reflect = global.Reflect || {};
global.Reflect.global = global.Reflect.global || global;
polyfillObject(global.Object);
}
setupGlobals(global);
global.$traceurRuntime = {
assertObject: assertObject,
createPrivateName: createPrivateName,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject,
privateNames: privateNames,
setProperty: setProperty,
setupGlobals: setupGlobals,
toObject: toObject,
isObject: isObject,
toProperty: toProperty,
type: types,
typeof: typeOf,
defineProperties: $defineProperties,
defineProperty: $defineProperty,
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
getOwnPropertyNames: $getOwnPropertyNames,
keys: $keys
};
})(typeof global !== 'undefined' ? global : this);
(function() {
'use strict';
function spread() {
var rv = [],
j = 0,
iterResult;
for (var i = 0; i < arguments.length; i++) {
var valueToSpread = arguments[i];
if (!$traceurRuntime.isObject(valueToSpread)) {
throw new TypeError('Cannot spread non-object.');
}
if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') {
throw new TypeError('Cannot spread non-iterable object.');
}
var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)]();
while (!(iterResult = iter.next()).done) {
rv[j++] = iterResult.value;
}
}
return rv;
}
$traceurRuntime.spread = spread;
})();
(function() {
'use strict';
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;
var $getPrototypeOf = Object.getPrototypeOf;
function superDescriptor(homeObject, name) {
var proto = $getPrototypeOf(homeObject);
do {
var result = $getOwnPropertyDescriptor(proto, name);
if (result)
return result;
proto = $getPrototypeOf(proto);
} while (proto);
return undefined;
}
function superCall(self, homeObject, name, args) {
return superGet(self, homeObject, name).apply(self, args);
}
function superGet(self, homeObject, name) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor) {
if (!descriptor.get)
return descriptor.value;
return descriptor.get.call(self);
}
return undefined;
}
function superSet(self, homeObject, name, value) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor && descriptor.set) {
descriptor.set.call(self, value);
return value;
}
throw $TypeError("super has no setter '" + name + "'.");
}
function getDescriptors(object) {
var descriptors = {},
name,
names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
descriptors[name] = $getOwnPropertyDescriptor(object, name);
}
return descriptors;
}
function createClass(ctor, object, staticObject, superClass) {
$defineProperty(object, 'constructor', {
value: ctor,
configurable: true,
enumerable: false,
writable: true
});
if (arguments.length > 3) {
if (typeof superClass === 'function')
ctor.__proto__ = superClass;
ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));
} else {
ctor.prototype = object;
}
$defineProperty(ctor, 'prototype', {
configurable: false,
writable: false
});
return $defineProperties(ctor, getDescriptors(staticObject));
}
function getProtoParent(superClass) {
if (typeof superClass === 'function') {
var prototype = superClass.prototype;
if ($Object(prototype) === prototype || prototype === null)
return superClass.prototype;
throw new $TypeError('super prototype must be an Object or null');
}
if (superClass === null)
return null;
throw new $TypeError('Super expression must either be null or a function');
}
function defaultSuperCall(self, homeObject, args) {
if ($getPrototypeOf(homeObject) !== null)
superCall(self, homeObject, 'constructor', args);
}
$traceurRuntime.createClass = createClass;
$traceurRuntime.defaultSuperCall = defaultSuperCall;
$traceurRuntime.superCall = superCall;
$traceurRuntime.superGet = superGet;
$traceurRuntime.superSet = superSet;
})();
(function() {
'use strict';
var createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $create = Object.create;
var $TypeError = TypeError;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;
var END_STATE = -2;
var RETHROW_STATE = -3;
function getInternalError(state) {
return new Error('Traceur compiler bug: invalid state in state machine: ' + state);
}
function GeneratorContext() {
this.state = 0;
this.GState = ST_NEWBORN;
this.storedException = undefined;
this.finallyFallThrough = undefined;
this.sent_ = undefined;
this.returnValue = undefined;
this.tryStack_ = [];
}
GeneratorContext.prototype = {
pushTry: function(catchState, finallyState) {
if (finallyState !== null) {
var finallyFallThrough = null;
for (var i = this.tryStack_.length - 1; i >= 0; i--) {
if (this.tryStack_[i].catch !== undefined) {
finallyFallThrough = this.tryStack_[i].catch;
break;
}
}
if (finallyFallThrough === null)
finallyFallThrough = RETHROW_STATE;
this.tryStack_.push({
finally: finallyState,
finallyFallThrough: finallyFallThrough
});
}
if (catchState !== null) {
this.tryStack_.push({catch: catchState});
}
},
popTry: function() {
this.tryStack_.pop();
},
get sent() {
this.maybeThrow();
return this.sent_;
},
set sent(v) {
this.sent_ = v;
},
get sentIgnoreThrow() {
return this.sent_;
},
maybeThrow: function() {
if (this.action === 'throw') {
this.action = 'next';
throw this.sent_;
}
},
end: function() {
switch (this.state) {
case END_STATE:
return this;
case RETHROW_STATE:
throw this.storedException;
default:
throw getInternalError(this.state);
}
},
handleException: function(ex) {
this.GState = ST_CLOSED;
this.state = END_STATE;
throw ex;
}
};
function nextOrThrow(ctx, moveNext, action, x) {
switch (ctx.GState) {
case ST_EXECUTING:
throw new Error(("\"" + action + "\" on executing generator"));
case ST_CLOSED:
if (action == 'next') {
return {
value: undefined,
done: true
};
}
throw x;
case ST_NEWBORN:
if (action === 'throw') {
ctx.GState = ST_CLOSED;
throw x;
}
if (x !== undefined)
throw $TypeError('Sent value to newborn generator');
case ST_SUSPENDED:
ctx.GState = ST_EXECUTING;
ctx.action = action;
ctx.sent = x;
var value = moveNext(ctx);
var done = value === ctx;
if (done)
value = ctx.returnValue;
ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
return {
value: value,
done: done
};
}
}
var ctxName = createPrivateName();
var moveNextName = createPrivateName();
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
GeneratorFunction.prototype = GeneratorFunctionPrototype;
$defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));
GeneratorFunctionPrototype.prototype = {
constructor: GeneratorFunctionPrototype,
next: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);
},
throw: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);
}
};
$defineProperties(GeneratorFunctionPrototype.prototype, {
constructor: {enumerable: false},
next: {enumerable: false},
throw: {enumerable: false}
});
Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {
return this;
}));
function createGeneratorInstance(innerFunction, functionObject, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new GeneratorContext();
var object = $create(functionObject.prototype);
object[ctxName] = ctx;
object[moveNextName] = moveNext;
return object;
}
function initGeneratorFunction(functionObject) {
functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);
functionObject.__proto__ = GeneratorFunctionPrototype;
return functionObject;
}
function AsyncFunctionContext() {
GeneratorContext.call(this);
this.err = undefined;
var ctx = this;
ctx.result = new Promise(function(resolve, reject) {
ctx.resolve = resolve;
ctx.reject = reject;
});
}
AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
switch (this.state) {
case END_STATE:
this.resolve(this.returnValue);
break;
case RETHROW_STATE:
this.reject(this.storedException);
break;
default:
this.reject(getInternalError(this.state));
}
};
AsyncFunctionContext.prototype.handleException = function() {
this.state = RETHROW_STATE;
};
function asyncWrap(innerFunction, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new AsyncFunctionContext();
ctx.createCallback = function(newState) {
return function(value) {
ctx.state = newState;
ctx.value = value;
moveNext(ctx);
};
};
ctx.errback = function(err) {
handleCatch(ctx, err);
moveNext(ctx);
};
moveNext(ctx);
return ctx.result;
}
function getMoveNext(innerFunction, self) {
return function(ctx) {
while (true) {
try {
return innerFunction.call(self, ctx);
} catch (ex) {
handleCatch(ctx, ex);
}
}
};
}
function handleCatch(ctx, ex) {
ctx.storedException = ex;
var last = ctx.tryStack_[ctx.tryStack_.length - 1];
if (!last) {
ctx.handleException(ex);
return;
}
ctx.state = last.catch !== undefined ? last.catch : last.finally;
if (last.finallyFallThrough !== undefined)
ctx.finallyFallThrough = last.finallyFallThrough;
}
$traceurRuntime.asyncWrap = asyncWrap;
$traceurRuntime.initGeneratorFunction = initGeneratorFunction;
$traceurRuntime.createGeneratorInstance = createGeneratorInstance;
})();
(function() {
function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
}
;
var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$');
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
function split(uri) {
return (uri.match(splitRe));
}
function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH] || '';
path = removeDotSegments(path);
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);
}
function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
function resolveUrl(base, url) {
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
function isAbsolute(name) {
if (!name)
return false;
if (name[0] === '/')
return true;
var parts = split(name);
if (parts[ComponentIndex.SCHEME])
return true;
return false;
}
$traceurRuntime.canonicalizeUrl = canonicalizeUrl;
$traceurRuntime.isAbsolute = isAbsolute;
$traceurRuntime.removeDotSegments = removeDotSegments;
$traceurRuntime.resolveUrl = resolveUrl;
})();
(function(global) {
'use strict';
var $__2 = $traceurRuntime.assertObject($traceurRuntime),
canonicalizeUrl = $__2.canonicalizeUrl,
resolveUrl = $__2.resolveUrl,
isAbsolute = $__2.isAbsolute;
var moduleInstantiators = Object.create(null);
var baseURL;
if (global.location && global.location.href)
baseURL = resolveUrl(global.location.href, './');
else
baseURL = '';
var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) {
this.url = url;
this.value_ = uncoatedModule;
};
($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {});
var ModuleEvaluationError = function ModuleEvaluationError(erroneousModuleName, cause) {
this.message = this.constructor.name + (cause ? ': \'' + cause + '\'' : '') + ' in ' + erroneousModuleName;
};
($traceurRuntime.createClass)(ModuleEvaluationError, {loadedBy: function(moduleName) {
this.message += '\n loaded by ' + moduleName;
}}, {}, Error);
var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) {
$traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]);
this.func = func;
};
var $UncoatedModuleInstantiator = UncoatedModuleInstantiator;
($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() {
if (this.value_)
return this.value_;
try {
return this.value_ = this.func.call(global);
} catch (ex) {
if (ex instanceof ModuleEvaluationError) {
ex.loadedBy(this.url);
throw ex;
}
throw new ModuleEvaluationError(this.url, ex);
}
}}, {}, UncoatedModuleEntry);
function getUncoatedModuleInstantiator(name) {
if (!name)
return;
var url = ModuleStore.normalize(name);
return moduleInstantiators[url];
}
;
var moduleInstances = Object.create(null);
var liveModuleSentinel = {};
function Module(uncoatedModule) {
var isLive = arguments[1];
var coatedModule = Object.create(null);
Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {
var getter,
value;
if (isLive === liveModuleSentinel) {
var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);
if (descr.get)
getter = descr.get;
}
if (!getter) {
value = uncoatedModule[name];
getter = function() {
return value;
};
}
Object.defineProperty(coatedModule, name, {
get: getter,
enumerable: true
});
}));
Object.preventExtensions(coatedModule);
return coatedModule;
}
var ModuleStore = {
normalize: function(name, refererName, refererAddress) {
if (typeof name !== "string")
throw new TypeError("module name must be a string, not " + typeof name);
if (isAbsolute(name))
return canonicalizeUrl(name);
if (/[^\.]\/\.\.\//.test(name)) {
throw new Error('module name embeds /../: ' + name);
}
if (name[0] === '.' && refererName)
return resolveUrl(refererName, name);
return canonicalizeUrl(name);
},
get: function(normalizedName) {
var m = getUncoatedModuleInstantiator(normalizedName);
if (!m)
return undefined;
var moduleInstance = moduleInstances[m.url];
if (moduleInstance)
return moduleInstance;
moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);
return moduleInstances[m.url] = moduleInstance;
},
set: function(normalizedName, module) {
normalizedName = String(normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {
return module;
}));
moduleInstances[normalizedName] = module;
},
get baseURL() {
return baseURL;
},
set baseURL(v) {
baseURL = String(v);
},
registerModule: function(name, func) {
var normalizedName = ModuleStore.normalize(name);
if (moduleInstantiators[normalizedName])
throw new Error('duplicate module named ' + normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);
},
bundleStore: Object.create(null),
register: function(name, deps, func) {
if (!deps || !deps.length && !func.length) {
this.registerModule(name, func);
} else {
this.bundleStore[name] = {
deps: deps,
execute: function() {
var $__0 = arguments;
var depMap = {};
deps.forEach((function(dep, index) {
return depMap[dep] = $__0[index];
}));
var registryEntry = func.call(this, depMap);
registryEntry.execute.call(this);
return registryEntry.exports;
}
};
}
},
getAnonymousModule: function(func) {
return new Module(func.call(global), liveModuleSentinel);
},
getForTesting: function(name) {
var $__0 = this;
if (!this.testingPrefix_) {
Object.keys(moduleInstances).some((function(key) {
var m = /(traceur@[^\/]*\/)/.exec(key);
if (m) {
$__0.testingPrefix_ = m[1];
return true;
}
}));
}
return this.get(this.testingPrefix_ + name);
}
};
ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore}));
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
};
$traceurRuntime.ModuleStore = ModuleStore;
global.System = {
register: ModuleStore.register.bind(ModuleStore),
get: ModuleStore.get,
set: ModuleStore.set,
normalize: ModuleStore.normalize
};
$traceurRuntime.getModuleImpl = function(name) {
var instantiator = getUncoatedModuleInstantiator(name);
return instantiator && instantiator.getUncoatedModule();
};
})(typeof global !== 'undefined' ? global : this);
System.register("traceur@0.0.52/src/runtime/polyfills/utils", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/utils";
var $ceil = Math.ceil;
var $floor = Math.floor;
var $isFinite = isFinite;
var $isNaN = isNaN;
var $pow = Math.pow;
var $min = Math.min;
var toObject = $traceurRuntime.toObject;
function toUint32(x) {
return x >>> 0;
}
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function isCallable(x) {
return typeof x === 'function';
}
function isNumber(x) {
return typeof x === 'number';
}
function toInteger(x) {
x = +x;
if ($isNaN(x))
return 0;
if (x === 0 || !$isFinite(x))
return x;
return x > 0 ? $floor(x) : $ceil(x);
}
var MAX_SAFE_LENGTH = $pow(2, 53) - 1;
function toLength(x) {
var len = toInteger(x);
return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH);
}
function checkIterable(x) {
return !isObject(x) ? undefined : x[Symbol.iterator];
}
function isConstructor(x) {
return isCallable(x);
}
return {
get toObject() {
return toObject;
},
get toUint32() {
return toUint32;
},
get isObject() {
return isObject;
},
get isCallable() {
return isCallable;
},
get isNumber() {
return isNumber;
},
get toInteger() {
return toInteger;
},
get toLength() {
return toLength;
},
get checkIterable() {
return checkIterable;
},
get isConstructor() {
return isConstructor;
}
};
});
System.register("traceur@0.0.52/src/runtime/polyfills/Array", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/Array";
var $__3 = System.get("traceur@0.0.52/src/runtime/polyfills/utils"),
isCallable = $__3.isCallable,
isConstructor = $__3.isConstructor,
checkIterable = $__3.checkIterable,
toInteger = $__3.toInteger,
toLength = $__3.toLength,
toObject = $__3.toObject;
function from(arrLike) {
var mapFn = arguments[1];
var thisArg = arguments[2];
var C = this;
var items = toObject(arrLike);
var mapping = mapFn !== undefined;
var k = 0;
var arr,
len;
if (mapping && !isCallable(mapFn)) {
throw TypeError();
}
if (checkIterable(items)) {
arr = isConstructor(C) ? new C() : [];
for (var $__4 = items[Symbol.iterator](),
$__5; !($__5 = $__4.next()).done; ) {
var item = $__5.value;
{
if (mapping) {
arr[k] = mapFn.call(thisArg, item, k);
} else {
arr[k] = item;
}
k++;
}
}
arr.length = k;
return arr;
}
len = toLength(items.length);
arr = isConstructor(C) ? new C(len) : new Array(len);
for (; k < len; k++) {
if (mapping) {
arr[k] = mapFn.call(thisArg, items[k], k);
} else {
arr[k] = items[k];
}
}
arr.length = len;
return arr;
}
function fill(value) {
var start = arguments[1] !== (void 0) ? arguments[1] : 0;
var end = arguments[2];
var object = toObject(this);
var len = toLength(object.length);
var fillStart = toInteger(start);
var fillEnd = end !== undefined ? toInteger(end) : len;
fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);
fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);
while (fillStart < fillEnd) {
object[fillStart] = value;
fillStart++;
}
return object;
}
function find(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg);
}
function findIndex(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg, true);
}
function findHelper(self, predicate) {
var thisArg = arguments[2];
var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;
var object = toObject(self);
var len = toLength(object.length);
if (!isCallable(predicate)) {
throw TypeError();
}
for (var i = 0; i < len; i++) {
if (i in object) {
var value = object[i];
if (predicate.call(thisArg, value, i, object)) {
return returnIndex ? i : value;
}
}
}
return returnIndex ? -1 : undefined;
}
return {
get from() {
return from;
},
get fill() {
return fill;
},
get find() {
return find;
},
get findIndex() {
return findIndex;
}
};
});
System.register("traceur@0.0.52/src/runtime/polyfills/ArrayIterator", [], function() {
"use strict";
var $__8;
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/ArrayIterator";
var $__6 = System.get("traceur@0.0.52/src/runtime/polyfills/utils"),
toObject = $__6.toObject,
toUint32 = $__6.toUint32;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function ArrayIterator() {};
($traceurRuntime.createClass)(ArrayIterator, ($__8 = {}, Object.defineProperty($__8, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__8, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__8), {});
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function createIteratorResultObject(value, done) {
return {
value: value,
done: done
};
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
return {
get entries() {
return entries;
},
get keys() {
return keys;
},
get values() {
return values;
}
};
});
System.register("traceur@0.0.52/src/runtime/polyfills/Map", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/Map";
var isObject = System.get("traceur@0.0.52/src/runtime/polyfills/utils").isObject;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
var deletedSentinel = {};
function lookupIndex(map, key) {
if (isObject(key)) {
var hashObject = getOwnHashObject(key);
return hashObject && map.objectIndex_[hashObject.hash];
}
if (typeof key === 'string')
return map.stringIndex_[key];
return map.primitiveIndex_[key];
}
function initMap(map) {
map.entries_ = [];
map.objectIndex_ = Object.create(null);
map.stringIndex_ = Object.create(null);
map.primitiveIndex_ = Object.create(null);
map.deletedCount_ = 0;
}
var Map = function Map() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Map called on incompatible type');
if ($hasOwnProperty.call(this, 'entries_')) {
throw new TypeError('Map can not be reentrantly initialised');
}
initMap(this);
if (iterable !== null && iterable !== undefined) {
for (var $__11 = iterable[Symbol.iterator](),
$__12; !($__12 = $__11.next()).done; ) {
var $__13 = $traceurRuntime.assertObject($__12.value),
key = $__13[0],
value = $__13[1];
{
this.set(key, value);
}
}
}
};
($traceurRuntime.createClass)(Map, {
get size() {
return this.entries_.length / 2 - this.deletedCount_;
},
get: function(key) {
var index = lookupIndex(this, key);
if (index !== undefined)
return this.entries_[index + 1];
},
set: function(key, value) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index = lookupIndex(this, key);
if (index !== undefined) {
this.entries_[index + 1] = value;
} else {
index = this.entries_.length;
this.entries_[index] = key;
this.entries_[index + 1] = value;
if (objectMode) {
var hashObject = getOwnHashObject(key);
var hash = hashObject.hash;
this.objectIndex_[hash] = index;
} else if (stringMode) {
this.stringIndex_[key] = index;
} else {
this.primitiveIndex_[key] = index;
}
}
return this;
},
has: function(key) {
return lookupIndex(this, key) !== undefined;
},
delete: function(key) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index;
var hash;
if (objectMode) {
var hashObject = getOwnHashObject(key);
if (hashObject) {
index = this.objectIndex_[hash = hashObject.hash];
delete this.objectIndex_[hash];
}
} else if (stringMode) {
index = this.stringIndex_[key];
delete this.stringIndex_[key];
} else {
index = this.primitiveIndex_[key];
delete this.primitiveIndex_[key];
}
if (index !== undefined) {
this.entries_[index] = deletedSentinel;
this.entries_[index + 1] = undefined;
this.deletedCount_++;
}
},
clear: function() {
initMap(this);
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
for (var i = 0,
len = this.entries_.length; i < len; i += 2) {
var key = this.entries_[i];
var value = this.entries_[i + 1];
if (key === deletedSentinel)
continue;
callbackFn.call(thisArg, value, key, this);
}
},
entries: $traceurRuntime.initGeneratorFunction(function $__14() {
var i,
len,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0, len = this.entries_.length;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < len) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return [key, value];
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__14, this);
}),
keys: $traceurRuntime.initGeneratorFunction(function $__15() {
var i,
len,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0, len = this.entries_.length;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < len) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return key;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__15, this);
}),
values: $traceurRuntime.initGeneratorFunction(function $__16() {
var i,
len,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0, len = this.entries_.length;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < len) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return value;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__16, this);
})
}, {});
Object.defineProperty(Map.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Map.prototype.entries
});
return {get Map() {
return Map;
}};
});
System.register("traceur@0.0.52/src/runtime/polyfills/Number", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/Number";
var $__17 = System.get("traceur@0.0.52/src/runtime/polyfills/utils"),
isNumber = $__17.isNumber,
toInteger = $__17.toInteger;
var $abs = Math.abs;
var $isFinite = isFinite;
var $isNaN = isNaN;
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1;
var EPSILON = Math.pow(2, -52);
function NumberIsFinite(number) {
return isNumber(number) && $isFinite(number);
}
;
function isInteger(number) {
return NumberIsFinite(number) && toInteger(number) === number;
}
function NumberIsNaN(number) {
return isNumber(number) && $isNaN(number);
}
;
function isSafeInteger(number) {
if (NumberIsFinite(number)) {
var integral = toInteger(number);
if (integral === number)
return $abs(integral) <= MAX_SAFE_INTEGER;
}
return false;
}
return {
get MAX_SAFE_INTEGER() {
return MAX_SAFE_INTEGER;
},
get MIN_SAFE_INTEGER() {
return MIN_SAFE_INTEGER;
},
get EPSILON() {
return EPSILON;
},
get isFinite() {
return NumberIsFinite;
},
get isInteger() {
return isInteger;
},
get isNaN() {
return NumberIsNaN;
},
get isSafeInteger() {
return isSafeInteger;
}
};
});
System.register("traceur@0.0.52/src/runtime/polyfills/Object", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/Object";
var $__18 = $traceurRuntime.assertObject($traceurRuntime),
defineProperty = $__18.defineProperty,
getOwnPropertyDescriptor = $__18.getOwnPropertyDescriptor,
getOwnPropertyNames = $__18.getOwnPropertyNames,
keys = $__18.keys,
privateNames = $__18.privateNames;
function is(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
return left !== left && right !== right;
}
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var props = keys(source);
var p,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
target[name] = source[name];
}
}
return target;
}
function mixin(target, source) {
var props = getOwnPropertyNames(source);
var p,
descriptor,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
descriptor = getOwnPropertyDescriptor(source, props[p]);
defineProperty(target, props[p], descriptor);
}
return target;
}
return {
get is() {
return is;
},
get assign() {
return assign;
},
get mixin() {
return mixin;
}
};
});
System.register("traceur@0.0.52/node_modules/rsvp/lib/rsvp/asap", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/node_modules/rsvp/lib/rsvp/asap";
var length = 0;
function asap(callback, arg) {
queue[length] = callback;
queue[length + 1] = arg;
length += 2;
if (length === 2) {
scheduleFlush();
}
}
var $__default = asap;
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {characterData: true});
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function() {
channel.port2.postMessage(0);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < length; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
length = 0;
}
var scheduleFlush;
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else {
scheduleFlush = useSetTimeout();
}
return {get default() {
return $__default;
}};
});
System.register("traceur@0.0.52/src/runtime/polyfills/Promise", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/Promise";
var async = System.get("traceur@0.0.52/node_modules/rsvp/lib/rsvp/asap").default;
var promiseRaw = {};
function isPromise(x) {
return x && typeof x === 'object' && x.status_ !== undefined;
}
function idResolveHandler(x) {
return x;
}
function idRejectHandler(x) {
throw x;
}
function chain(promise) {
var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;
var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;
var deferred = getDeferred(promise.constructor);
switch (promise.status_) {
case undefined:
throw TypeError;
case 0:
promise.onResolve_.push(onResolve, deferred);
promise.onReject_.push(onReject, deferred);
break;
case +1:
promiseEnqueue(promise.value_, [onResolve, deferred]);
break;
case -1:
promiseEnqueue(promise.value_, [onReject, deferred]);
break;
}
return deferred.promise;
}
function getDeferred(C) {
if (this === $Promise) {
var promise = promiseInit(new $Promise(promiseRaw));
return {
promise: promise,
resolve: (function(x) {
promiseResolve(promise, x);
}),
reject: (function(r) {
promiseReject(promise, r);
})
};
} else {
var result = {};
result.promise = new C((function(resolve, reject) {
result.resolve = resolve;
result.reject = reject;
}));
return result;
}
}
function promiseSet(promise, status, value, onResolve, onReject) {
promise.status_ = status;
promise.value_ = value;
promise.onResolve_ = onResolve;
promise.onReject_ = onReject;
return promise;
}
function promiseInit(promise) {
return promiseSet(promise, 0, undefined, [], []);
}
var Promise = function Promise(resolver) {
if (resolver === promiseRaw)
return;
if (typeof resolver !== 'function')
throw new TypeError;
var promise = promiseInit(this);
try {
resolver((function(x) {
promiseResolve(promise, x);
}), (function(r) {
promiseReject(promise, r);
}));
} catch (e) {
promiseReject(promise, e);
}
};
($traceurRuntime.createClass)(Promise, {
catch: function(onReject) {
return this.then(undefined, onReject);
},
then: function(onResolve, onReject) {
if (typeof onResolve !== 'function')
onResolve = idResolveHandler;
if (typeof onReject !== 'function')
onReject = idRejectHandler;
var that = this;
var constructor = this.constructor;
return chain(this, function(x) {
x = promiseCoerce(constructor, x);
return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);
}, onReject);
}
}, {
resolve: function(x) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), +1, x);
} else {
return new this(function(resolve, reject) {
resolve(x);
});
}
},
reject: function(r) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), -1, r);
} else {
return new this((function(resolve, reject) {
reject(r);
}));
}
},
cast: function(x) {
if (x instanceof this)
return x;
if (isPromise(x)) {
var result = getDeferred(this);
chain(x, result.resolve, result.reject);
return result.promise;
}
return this.resolve(x);
},
all: function(values) {
var deferred = getDeferred(this);
var resolutions = [];
try {
var count = values.length;
if (count === 0) {
deferred.resolve(resolutions);
} else {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then(function(i, x) {
resolutions[i] = x;
if (--count === 0)
deferred.resolve(resolutions);
}.bind(undefined, i), (function(r) {
deferred.reject(r);
}));
}
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
},
race: function(values) {
var deferred = getDeferred(this);
try {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then((function(x) {
deferred.resolve(x);
}), (function(r) {
deferred.reject(r);
}));
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
}
});
var $Promise = Promise;
var $PromiseReject = $Promise.reject;
function promiseResolve(promise, x) {
promiseDone(promise, +1, x, promise.onResolve_);
}
function promiseReject(promise, r) {
promiseDone(promise, -1, r, promise.onReject_);
}
function promiseDone(promise, status, value, reactions) {
if (promise.status_ !== 0)
return;
promiseEnqueue(value, reactions);
promiseSet(promise, status, value);
}
function promiseEnqueue(value, tasks) {
async((function() {
for (var i = 0; i < tasks.length; i += 2) {
promiseHandle(value, tasks[i], tasks[i + 1]);
}
}));
}
function promiseHandle(value, handler, deferred) {
try {
var result = handler(value);
if (result === deferred.promise)
throw new TypeError;
else if (isPromise(result))
chain(result, deferred.resolve, deferred.reject);
else
deferred.resolve(result);
} catch (e) {
try {
deferred.reject(e);
} catch (e) {}
}
}
var thenableSymbol = '@@thenable';
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function promiseCoerce(constructor, x) {
if (!isPromise(x) && isObject(x)) {
var then;
try {
then = x.then;
} catch (r) {
var promise = $PromiseReject.call(constructor, r);
x[thenableSymbol] = promise;
return promise;
}
if (typeof then === 'function') {
var p = x[thenableSymbol];
if (p) {
return p;
} else {
var deferred = getDeferred(constructor);
x[thenableSymbol] = deferred.promise;
try {
then.call(x, deferred.resolve, deferred.reject);
} catch (r) {
deferred.reject(r);
}
return deferred.promise;
}
}
}
return x;
}
return {get Promise() {
return Promise;
}};
});
System.register("traceur@0.0.52/src/runtime/polyfills/Set", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/Set";
var isObject = System.get("traceur@0.0.52/src/runtime/polyfills/utils").isObject;
var Map = System.get("traceur@0.0.52/src/runtime/polyfills/Map").Map;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
function initSet(set) {
set.map_ = new Map();
}
var Set = function Set() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Set called on incompatible type');
if ($hasOwnProperty.call(this, 'map_')) {
throw new TypeError('Set can not be reentrantly initialised');
}
initSet(this);
if (iterable !== null && iterable !== undefined) {
for (var $__25 = iterable[Symbol.iterator](),
$__26; !($__26 = $__25.next()).done; ) {
var item = $__26.value;
{
this.add(item);
}
}
}
};
($traceurRuntime.createClass)(Set, {
get size() {
return this.map_.size;
},
has: function(key) {
return this.map_.has(key);
},
add: function(key) {
return this.map_.set(key, key);
},
delete: function(key) {
return this.map_.delete(key);
},
clear: function() {
return this.map_.clear();
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
var $__23 = this;
return this.map_.forEach((function(value, key) {
callbackFn.call(thisArg, key, key, $__23);
}));
},
values: $traceurRuntime.initGeneratorFunction(function $__27() {
var $__28,
$__29;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__28 = this.map_.keys()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__29 = $__28[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__29.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__29.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__29.value;
default:
return $ctx.end();
}
}, $__27, this);
}),
entries: $traceurRuntime.initGeneratorFunction(function $__30() {
var $__31,
$__32;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__31 = this.map_.entries()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__32 = $__31[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__32.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__32.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__32.value;
default:
return $ctx.end();
}
}, $__30, this);
})
}, {});
Object.defineProperty(Set.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Set.prototype.values
});
Object.defineProperty(Set.prototype, 'keys', {
configurable: true,
writable: true,
value: Set.prototype.values
});
return {get Set() {
return Set;
}};
});
System.register("traceur@0.0.52/src/runtime/polyfills/String", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/String";
var $toString = Object.prototype.toString;
var $indexOf = String.prototype.indexOf;
var $lastIndexOf = String.prototype.lastIndexOf;
function startsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) == start;
}
function endsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var pos = stringLength;
if (arguments.length > 1) {
var position = arguments[1];
if (position !== undefined) {
pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
}
}
var end = Math.min(Math.max(pos, 0), stringLength);
var start = end - searchLength;
if (start < 0) {
return false;
}
return $lastIndexOf.call(string, searchString, start) == start;
}
function contains(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) != -1;
}
function repeat(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var n = count ? Number(count) : 0;
if (isNaN(n)) {
n = 0;
}
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
}
function codePointAt(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
var index = position ? Number(position) : 0;
if (isNaN(index)) {
index = 0;
}
if (index < 0 || index >= size) {
return undefined;
}
var first = string.charCodeAt(index);
var second;
if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
}
function raw(callsite) {
var raw = callsite.raw;
var len = raw.length >>> 0;
if (len === 0)
return '';
var s = '';
var i = 0;
while (true) {
s += raw[i];
if (i + 1 === len)
return s;
s += arguments[++i];
}
}
function fromCodePoint() {
var codeUnits = [];
var floor = Math.floor;
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
codeUnits.push(codePoint);
} else {
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
}
return String.fromCharCode.apply(null, codeUnits);
}
return {
get startsWith() {
return startsWith;
},
get endsWith() {
return endsWith;
},
get contains() {
return contains;
},
get repeat() {
return repeat;
},
get codePointAt() {
return codePointAt;
},
get raw() {
return raw;
},
get fromCodePoint() {
return fromCodePoint;
}
};
});
System.register("traceur@0.0.52/src/runtime/polyfills/polyfills", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfills/polyfills";
var Map = System.get("traceur@0.0.52/src/runtime/polyfills/Map").Map;
var Set = System.get("traceur@0.0.52/src/runtime/polyfills/Set").Set;
var Promise = System.get("traceur@0.0.52/src/runtime/polyfills/Promise").Promise;
var $__36 = System.get("traceur@0.0.52/src/runtime/polyfills/String"),
codePointAt = $__36.codePointAt,
contains = $__36.contains,
endsWith = $__36.endsWith,
fromCodePoint = $__36.fromCodePoint,
repeat = $__36.repeat,
raw = $__36.raw,
startsWith = $__36.startsWith;
var $__37 = System.get("traceur@0.0.52/src/runtime/polyfills/Array"),
fill = $__37.fill,
find = $__37.find,
findIndex = $__37.findIndex,
from = $__37.from;
var $__38 = System.get("traceur@0.0.52/src/runtime/polyfills/ArrayIterator"),
entries = $__38.entries,
keys = $__38.keys,
values = $__38.values;
var $__39 = System.get("traceur@0.0.52/src/runtime/polyfills/Object"),
assign = $__39.assign,
is = $__39.is,
mixin = $__39.mixin;
var $__40 = System.get("traceur@0.0.52/src/runtime/polyfills/Number"),
MAX_SAFE_INTEGER = $__40.MAX_SAFE_INTEGER,
MIN_SAFE_INTEGER = $__40.MIN_SAFE_INTEGER,
EPSILON = $__40.EPSILON,
isFinite = $__40.isFinite,
isInteger = $__40.isInteger,
isNaN = $__40.isNaN,
isSafeInteger = $__40.isSafeInteger;
var getPrototypeOf = $traceurRuntime.assertObject(Object).getPrototypeOf;
function maybeDefine(object, name, descr) {
if (!(name in object)) {
Object.defineProperty(object, name, descr);
}
}
function maybeDefineMethod(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
function maybeDefineConst(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: false,
enumerable: false,
writable: false
});
}
function maybeAddFunctions(object, functions) {
for (var i = 0; i < functions.length; i += 2) {
var name = functions[i];
var value = functions[i + 1];
maybeDefineMethod(object, name, value);
}
}
function maybeAddConsts(object, consts) {
for (var i = 0; i < consts.length; i += 2) {
var name = consts[i];
var value = consts[i + 1];
maybeDefineConst(object, name, value);
}
}
function maybeAddIterator(object, func, Symbol) {
if (!Symbol || !Symbol.iterator || object[Symbol.iterator])
return;
if (object['@@iterator'])
func = object['@@iterator'];
Object.defineProperty(object, Symbol.iterator, {
value: func,
configurable: true,
enumerable: false,
writable: true
});
}
function polyfillPromise(global) {
if (!global.Promise)
global.Promise = Promise;
}
function polyfillCollections(global, Symbol) {
if (!global.Map)
global.Map = Map;
var mapPrototype = global.Map.prototype;
if (mapPrototype.entries) {
maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol);
maybeAddIterator(getPrototypeOf(new global.Map().entries()), function() {
return this;
}, Symbol);
}
if (!global.Set)
global.Set = Set;
var setPrototype = global.Set.prototype;
if (setPrototype.values) {
maybeAddIterator(setPrototype, setPrototype.values, Symbol);
maybeAddIterator(getPrototypeOf(new global.Set().values()), function() {
return this;
}, Symbol);
}
}
function polyfillString(String) {
maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]);
maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);
}
function polyfillArray(Array, Symbol) {
maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);
maybeAddFunctions(Array, ['from', from]);
maybeAddIterator(Array.prototype, values, Symbol);
maybeAddIterator(getPrototypeOf([].values()), function() {
return this;
}, Symbol);
}
function polyfillObject(Object) {
maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);
}
function polyfillNumber(Number) {
maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]);
maybeAddFunctions(Number, ['isFinite', isFinite, 'isInteger', isInteger, 'isNaN', isNaN, 'isSafeInteger', isSafeInteger]);
}
function polyfill(global) {
polyfillPromise(global);
polyfillCollections(global, global.Symbol);
polyfillString(global.String);
polyfillArray(global.Array, global.Symbol);
polyfillObject(global.Object);
polyfillNumber(global.Number);
}
polyfill(this);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
polyfill(global);
};
return {};
});
System.register("traceur@0.0.52/src/runtime/polyfill-import", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/polyfill-import";
System.get("traceur@0.0.52/src/runtime/polyfills/polyfills");
return {};
});
System.get("traceur@0.0.52/src/runtime/polyfill-import" + '');
System.register("traceur@0.0.52/src/Options", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/Options";
function enumerableOnlyObject(obj) {
var result = Object.create(null);
Object.keys(obj).forEach(function(key) {
Object.defineProperty(result, key, {
enumerable: true,
value: obj[key]
});
});
return result;
}
var optionsV01 = enumerableOnlyObject({
arrayComprehension: true,
arrowFunctions: true,
classes: true,
computedPropertyNames: true,
defaultParameters: true,
destructuring: true,
forOf: true,
generatorComprehension: true,
generators: true,
modules: 'register',
numericLiterals: true,
propertyMethods: true,
propertyNameShorthand: true,
restParameters: true,
spread: true,
templateLiterals: true,
asyncFunctions: false,
blockBinding: false,
symbols: false,
types: false,
annotations: false,
commentCallback: false,
debug: false,
freeVariableChecker: false,
sourceMaps: false,
typeAssertions: false,
validate: false,
referrer: '',
typeAssertionModule: null,
moduleName: false,
outputLanguage: 'es5',
filename: undefined
});
var versionLockedOptions = optionsV01;
var parseOptions = Object.create(null);
var transformOptions = Object.create(null);
var defaultValues = Object.create(null);
var experimentalOptions = Object.create(null);
var moduleOptions = ['amd', 'commonjs', 'instantiate', 'inline', 'register'];
var Options = function Options() {
var options = arguments[0] !== (void 0) ? arguments[0] : Object.create(null);
this.setDefaults();
this.setFromObject(versionLockedOptions);
this.setFromObject(options);
Object.defineProperties(this, {modules_: {
value: versionLockedOptions.modules,
writable: true,
enumerable: false
}});
};
($traceurRuntime.createClass)(Options, {
set experimental(v) {
var $__42 = this;
v = coerceOptionValue(v);
Object.keys(experimentalOptions).forEach((function(name) {
$__42[name] = v;
}));
},
get experimental() {
var $__42 = this;
var value;
Object.keys(experimentalOptions).every((function(name) {
var currentValue = $__42[name];
if (value === undefined) {
value = currentValue;
return true;
}
if (currentValue !== value) {
value = null;
return false;
}
return true;
}));
return value;
},
get modules() {
return this.modules_;
},
set modules(value) {
if (typeof value === 'boolean' && !value)
value = 'register';
if (moduleOptions.indexOf(value) === -1) {
throw new Error('Invalid \'modules\' option \'' + value + '\', not in ' + moduleOptions.join(', '));
}
this.modules_ = value;
},
reset: function() {
var allOff = arguments[0];
var $__42 = this;
var useDefault = allOff === undefined;
Object.keys(this).forEach((function(name) {
$__42[name] = useDefault && defaultValues[name];
}));
this.setDefaults();
},
setDefaults: function() {
this.modules = 'register';
this.moduleName = false;
this.outputLanguage = 'es5';
this.filename = undefined;
},
setFromObject: function(object) {
var $__42 = this;
Object.keys(object).forEach((function(name) {
$__42[name] = object[name];
}));
this.modules = object.modules || this.modules;
return this;
}
}, {});
;
var options = new Options();
var descriptions = {
experimental: 'Turns on all experimental features',
sourceMaps: 'generate source map and write to .map'
};
var CommandOptions = function CommandOptions() {
$traceurRuntime.defaultSuperCall(this, $CommandOptions.prototype, arguments);
};
var $CommandOptions = CommandOptions;
($traceurRuntime.createClass)(CommandOptions, {
parseCommand: function(s) {
var re = /--([^=]+)(?:=(.+))?/;
var m = re.exec(s);
if (m)
this.setOption(m[1], m[2] || true);
},
setOption: function(name, value) {
name = toCamelCase(name);
value = coerceOptionValue(value);
if (name in this) {
this[name] = value;
} else {
throw Error('Unknown option: ' + name);
}
}
}, {
fromString: function(s) {
return $CommandOptions.fromArgv(s.split(/\s+/));
},
fromArgv: function(args) {
var options = new $CommandOptions();
args.forEach((function(arg) {
return options.parseCommand(arg);
}));
return options;
}
}, Options);
function coerceOptionValue(v) {
switch (v) {
case 'false':
return false;
case 'true':
case true:
return true;
default:
return !!v && String(v);
}
}
function addOptions(flags, commandOptions) {
flags.option('--referrer <name>', 'Bracket output code with System.referrerName=<name>', (function(name) {
commandOptions.setOption('referrer', name);
System.map = System.semverMap(name);
return name;
}));
flags.option('--type-assertion-module <path>', 'Absolute path to the type assertion module.', (function(path) {
commandOptions.setOption('type-assertion-module', path);
return path;
}));
flags.option('--modules <' + moduleOptions.join(', ') + '>', 'select the output format for modules', (function(moduleFormat) {
commandOptions.modules = moduleFormat;
}));
flags.option('--moduleName <string>', '__moduleName value, + sign to use filename, or empty to omit; default +', (function(moduleName) {
if (moduleName === '+')
moduleName = true;
commandOptions.moduleName = moduleName;
}));
flags.option('--outputLanguage <es6|es5>', 'compilation target language', (function(outputLanguage) {
if (outputLanguage === 'es6' || outputLanguage === 'es5')
commandOptions.outputLanguage = outputLanguage;
else
throw new Error('outputLanguage must be one of es5, es6');
}));
flags.option('--experimental ', 'Turns on all experimental features', (function() {
commandOptions.experimental = true;
}));
Object.keys(commandOptions).forEach(function(name) {
var dashedName = toDashCase(name);
if (flags.optionFor('--' + name) || flags.optionFor('--' + dashedName)) {
return;
} else if ((name in parseOptions) && (name in transformOptions)) {
flags.option('--' + dashedName + ' [true|false|parse]', descriptions[name]);
flags.on(dashedName, (function(value) {
return commandOptions.setOption(dashedName, value);
}));
} else if (commandOptions[name] !== null) {
flags.option('--' + dashedName, descriptions[name]);
flags.on(dashedName, (function() {
return commandOptions.setOption(dashedName, true);
}));
} else {
throw new Error('Unexpected null commandOption ' + name);
}
});
commandOptions.setDefaults();
}
function toCamelCase(s) {
return s.replace(/-\w/g, function(ch) {
return ch[1].toUpperCase();
});
}
function toDashCase(s) {
return s.replace(/[A-Z]/g, function(ch) {
return '-' + ch.toLowerCase();
});
}
var EXPERIMENTAL = 0;
var ON_BY_DEFAULT = 1;
function addFeatureOption(name, kind) {
if (kind === EXPERIMENTAL)
experimentalOptions[name] = true;
Object.defineProperty(parseOptions, name, {
get: function() {
return !!options[name];
},
enumerable: true,
configurable: true
});
Object.defineProperty(transformOptions, name, {
get: function() {
var v = options[name];
if (v === 'parse')
return false;
return v;
},
enumerable: true,
configurable: true
});
var defaultValue = options[name] || kind === ON_BY_DEFAULT;
options[name] = defaultValue;
defaultValues[name] = defaultValue;
}
function addBoolOption(name) {
defaultValues[name] = false;
options[name] = false;
}
addFeatureOption('arrayComprehension', ON_BY_DEFAULT);
addFeatureOption('arrowFunctions', ON_BY_DEFAULT);
addFeatureOption('classes', ON_BY_DEFAULT);
addFeatureOption('computedPropertyNames', ON_BY_DEFAULT);
addFeatureOption('defaultParameters', ON_BY_DEFAULT);
addFeatureOption('destructuring', ON_BY_DEFAULT);
addFeatureOption('forOf', ON_BY_DEFAULT);
addFeatureOption('generatorComprehension', ON_BY_DEFAULT);
addFeatureOption('generators', ON_BY_DEFAULT);
addFeatureOption('modules', 'SPECIAL');
addFeatureOption('numericLiterals', ON_BY_DEFAULT);
addFeatureOption('propertyMethods', ON_BY_DEFAULT);
addFeatureOption('propertyNameShorthand', ON_BY_DEFAULT);
addFeatureOption('restParameters', ON_BY_DEFAULT);
addFeatureOption('spread', ON_BY_DEFAULT);
addFeatureOption('templateLiterals', ON_BY_DEFAULT);
addFeatureOption('asyncFunctions', EXPERIMENTAL);
addFeatureOption('blockBinding', EXPERIMENTAL);
addFeatureOption('symbols', EXPERIMENTAL);
addFeatureOption('types', EXPERIMENTAL);
addFeatureOption('annotations', EXPERIMENTAL);
addBoolOption('commentCallback');
addBoolOption('debug');
addBoolOption('freeVariableChecker');
addBoolOption('sourceMaps');
addBoolOption('typeAssertions');
addBoolOption('validate');
defaultValues.referrer = '';
options.referrer = null;
defaultValues.typeAssertionModule = null;
options.typeAssertionModule = null;
return {
get optionsV01() {
return optionsV01;
},
get versionLockedOptions() {
return versionLockedOptions;
},
get parseOptions() {
return parseOptions;
},
get transformOptions() {
return transformOptions;
},
get Options() {
return Options;
},
get options() {
return options;
},
get CommandOptions() {
return CommandOptions;
},
get addOptions() {
return addOptions;
}
};
});
System.register("traceur@0.0.52/src/syntax/TokenType", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/TokenType";
var AMPERSAND = '&';
var AMPERSAND_EQUAL = '&=';
var AND = '&&';
var ARROW = '=>';
var AT = '@';
var BACK_QUOTE = '`';
var BANG = '!';
var BAR = '|';
var BAR_EQUAL = '|=';
var BREAK = 'break';
var CARET = '^';
var CARET_EQUAL = '^=';
var CASE = 'case';
var CATCH = 'catch';
var CLASS = 'class';
var CLOSE_ANGLE = '>';
var CLOSE_CURLY = '}';
var CLOSE_PAREN = ')';
var CLOSE_SQUARE = ']';
var COLON = ':';
var COMMA = ',';
var CONST = 'const';
var CONTINUE = 'continue';
var DEBUGGER = 'debugger';
var DEFAULT = 'default';
var DELETE = 'delete';
var DO = 'do';
var DOT_DOT_DOT = '...';
var ELSE = 'else';
var END_OF_FILE = 'End of File';
var ENUM = 'enum';
var EQUAL = '=';
var EQUAL_EQUAL = '==';
var EQUAL_EQUAL_EQUAL = '===';
var ERROR = 'error';
var EXPORT = 'export';
var EXTENDS = 'extends';
var FALSE = 'false';
var FINALLY = 'finally';
var FOR = 'for';
var FUNCTION = 'function';
var GREATER_EQUAL = '>=';
var IDENTIFIER = 'identifier';
var IF = 'if';
var IMPLEMENTS = 'implements';
var IMPORT = 'import';
var IN = 'in';
var INSTANCEOF = 'instanceof';
var INTERFACE = 'interface';
var LEFT_SHIFT = '<<';
var LEFT_SHIFT_EQUAL = '<<=';
var LESS_EQUAL = '<=';
var LET = 'let';
var MINUS = '-';
var MINUS_EQUAL = '-=';
var MINUS_MINUS = '--';
var NEW = 'new';
var NO_SUBSTITUTION_TEMPLATE = 'no substitution template';
var NOT_EQUAL = '!=';
var NOT_EQUAL_EQUAL = '!==';
var NULL = 'null';
var NUMBER = 'number literal';
var OPEN_ANGLE = '<';
var OPEN_CURLY = '{';
var OPEN_PAREN = '(';
var OPEN_SQUARE = '[';
var OR = '||';
var PACKAGE = 'package';
var PERCENT = '%';
var PERCENT_EQUAL = '%=';
var PERIOD = '.';
var PLUS = '+';
var PLUS_EQUAL = '+=';
var PLUS_PLUS = '++';
var PRIVATE = 'private';
var PROTECTED = 'protected';
var PUBLIC = 'public';
var QUESTION = '?';
var REGULAR_EXPRESSION = 'regular expression literal';
var RETURN = 'return';
var RIGHT_SHIFT = '>>';
var RIGHT_SHIFT_EQUAL = '>>=';
var SEMI_COLON = ';';
var SLASH = '/';
var SLASH_EQUAL = '/=';
var STAR = '*';
var STAR_EQUAL = '*=';
var STATIC = 'static';
var STRING = 'string literal';
var SUPER = 'super';
var SWITCH = 'switch';
var TEMPLATE_HEAD = 'template head';
var TEMPLATE_MIDDLE = 'template middle';
var TEMPLATE_TAIL = 'template tail';
var THIS = 'this';
var THROW = 'throw';
var TILDE = '~';
var TRUE = 'true';
var TRY = 'try';
var TYPEOF = 'typeof';
var UNSIGNED_RIGHT_SHIFT = '>>>';
var UNSIGNED_RIGHT_SHIFT_EQUAL = '>>>=';
var VAR = 'var';
var VOID = 'void';
var WHILE = 'while';
var WITH = 'with';
var YIELD = 'yield';
return {
get AMPERSAND() {
return AMPERSAND;
},
get AMPERSAND_EQUAL() {
return AMPERSAND_EQUAL;
},
get AND() {
return AND;
},
get ARROW() {
return ARROW;
},
get AT() {
return AT;
},
get BACK_QUOTE() {
return BACK_QUOTE;
},
get BANG() {
return BANG;
},
get BAR() {
return BAR;
},
get BAR_EQUAL() {
return BAR_EQUAL;
},
get BREAK() {
return BREAK;
},
get CARET() {
return CARET;
},
get CARET_EQUAL() {
return CARET_EQUAL;
},
get CASE() {
return CASE;
},
get CATCH() {
return CATCH;
},
get CLASS() {
return CLASS;
},
get CLOSE_ANGLE() {
return CLOSE_ANGLE;
},
get CLOSE_CURLY() {
return CLOSE_CURLY;
},
get CLOSE_PAREN() {
return CLOSE_PAREN;
},
get CLOSE_SQUARE() {
return CLOSE_SQUARE;
},
get COLON() {
return COLON;
},
get COMMA() {
return COMMA;
},
get CONST() {
return CONST;
},
get CONTINUE() {
return CONTINUE;
},
get DEBUGGER() {
return DEBUGGER;
},
get DEFAULT() {
return DEFAULT;
},
get DELETE() {
return DELETE;
},
get DO() {
return DO;
},
get DOT_DOT_DOT() {
return DOT_DOT_DOT;
},
get ELSE() {
return ELSE;
},
get END_OF_FILE() {
return END_OF_FILE;
},
get ENUM() {
return ENUM;
},
get EQUAL() {
return EQUAL;
},
get EQUAL_EQUAL() {
return EQUAL_EQUAL;
},
get EQUAL_EQUAL_EQUAL() {
return EQUAL_EQUAL_EQUAL;
},
get ERROR() {
return ERROR;
},
get EXPORT() {
return EXPORT;
},
get EXTENDS() {
return EXTENDS;
},
get FALSE() {
return FALSE;
},
get FINALLY() {
return FINALLY;
},
get FOR() {
return FOR;
},
get FUNCTION() {
return FUNCTION;
},
get GREATER_EQUAL() {
return GREATER_EQUAL;
},
get IDENTIFIER() {
return IDENTIFIER;
},
get IF() {
return IF;
},
get IMPLEMENTS() {
return IMPLEMENTS;
},
get IMPORT() {
return IMPORT;
},
get IN() {
return IN;
},
get INSTANCEOF() {
return INSTANCEOF;
},
get INTERFACE() {
return INTERFACE;
},
get LEFT_SHIFT() {
return LEFT_SHIFT;
},
get LEFT_SHIFT_EQUAL() {
return LEFT_SHIFT_EQUAL;
},
get LESS_EQUAL() {
return LESS_EQUAL;
},
get LET() {
return LET;
},
get MINUS() {
return MINUS;
},
get MINUS_EQUAL() {
return MINUS_EQUAL;
},
get MINUS_MINUS() {
return MINUS_MINUS;
},
get NEW() {
return NEW;
},
get NO_SUBSTITUTION_TEMPLATE() {
return NO_SUBSTITUTION_TEMPLATE;
},
get NOT_EQUAL() {
return NOT_EQUAL;
},
get NOT_EQUAL_EQUAL() {
return NOT_EQUAL_EQUAL;
},
get NULL() {
return NULL;
},
get NUMBER() {
return NUMBER;
},
get OPEN_ANGLE() {
return OPEN_ANGLE;
},
get OPEN_CURLY() {
return OPEN_CURLY;
},
get OPEN_PAREN() {
return OPEN_PAREN;
},
get OPEN_SQUARE() {
return OPEN_SQUARE;
},
get OR() {
return OR;
},
get PACKAGE() {
return PACKAGE;
},
get PERCENT() {
return PERCENT;
},
get PERCENT_EQUAL() {
return PERCENT_EQUAL;
},
get PERIOD() {
return PERIOD;
},
get PLUS() {
return PLUS;
},
get PLUS_EQUAL() {
return PLUS_EQUAL;
},
get PLUS_PLUS() {
return PLUS_PLUS;
},
get PRIVATE() {
return PRIVATE;
},
get PROTECTED() {
return PROTECTED;
},
get PUBLIC() {
return PUBLIC;
},
get QUESTION() {
return QUESTION;
},
get REGULAR_EXPRESSION() {
return REGULAR_EXPRESSION;
},
get RETURN() {
return RETURN;
},
get RIGHT_SHIFT() {
return RIGHT_SHIFT;
},
get RIGHT_SHIFT_EQUAL() {
return RIGHT_SHIFT_EQUAL;
},
get SEMI_COLON() {
return SEMI_COLON;
},
get SLASH() {
return SLASH;
},
get SLASH_EQUAL() {
return SLASH_EQUAL;
},
get STAR() {
return STAR;
},
get STAR_EQUAL() {
return STAR_EQUAL;
},
get STATIC() {
return STATIC;
},
get STRING() {
return STRING;
},
get SUPER() {
return SUPER;
},
get SWITCH() {
return SWITCH;
},
get TEMPLATE_HEAD() {
return TEMPLATE_HEAD;
},
get TEMPLATE_MIDDLE() {
return TEMPLATE_MIDDLE;
},
get TEMPLATE_TAIL() {
return TEMPLATE_TAIL;
},
get THIS() {
return THIS;
},
get THROW() {
return THROW;
},
get TILDE() {
return TILDE;
},
get TRUE() {
return TRUE;
},
get TRY() {
return TRY;
},
get TYPEOF() {
return TYPEOF;
},
get UNSIGNED_RIGHT_SHIFT() {
return UNSIGNED_RIGHT_SHIFT;
},
get UNSIGNED_RIGHT_SHIFT_EQUAL() {
return UNSIGNED_RIGHT_SHIFT_EQUAL;
},
get VAR() {
return VAR;
},
get VOID() {
return VOID;
},
get WHILE() {
return WHILE;
},
get WITH() {
return WITH;
},
get YIELD() {
return YIELD;
}
};
});
System.register("traceur@0.0.52/src/syntax/trees/ParseTreeType", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/trees/ParseTreeType";
var ANNOTATION = 'ANNOTATION';
var ANON_BLOCK = 'ANON_BLOCK';
var ARGUMENT_LIST = 'ARGUMENT_LIST';
var ARRAY_COMPREHENSION = 'ARRAY_COMPREHENSION';
var ARRAY_LITERAL_EXPRESSION = 'ARRAY_LITERAL_EXPRESSION';
var ARRAY_PATTERN = 'ARRAY_PATTERN';
var ARROW_FUNCTION_EXPRESSION = 'ARROW_FUNCTION_EXPRESSION';
var ASSIGNMENT_ELEMENT = 'ASSIGNMENT_ELEMENT';
var AWAIT_EXPRESSION = 'AWAIT_EXPRESSION';
var BINARY_EXPRESSION = 'BINARY_EXPRESSION';
var BINDING_ELEMENT = 'BINDING_ELEMENT';
var BINDING_IDENTIFIER = 'BINDING_IDENTIFIER';
var BLOCK = 'BLOCK';
var BREAK_STATEMENT = 'BREAK_STATEMENT';
var CALL_EXPRESSION = 'CALL_EXPRESSION';
var CASE_CLAUSE = 'CASE_CLAUSE';
var CATCH = 'CATCH';
var CLASS_DECLARATION = 'CLASS_DECLARATION';
var CLASS_EXPRESSION = 'CLASS_EXPRESSION';
var COMMA_EXPRESSION = 'COMMA_EXPRESSION';
var COMPREHENSION_FOR = 'COMPREHENSION_FOR';
var COMPREHENSION_IF = 'COMPREHENSION_IF';
var COMPUTED_PROPERTY_NAME = 'COMPUTED_PROPERTY_NAME';
var CONDITIONAL_EXPRESSION = 'CONDITIONAL_EXPRESSION';
var CONTINUE_STATEMENT = 'CONTINUE_STATEMENT';
var COVER_FORMALS = 'COVER_FORMALS';
var COVER_INITIALIZED_NAME = 'COVER_INITIALIZED_NAME';
var DEBUGGER_STATEMENT = 'DEBUGGER_STATEMENT';
var DEFAULT_CLAUSE = 'DEFAULT_CLAUSE';
var DO_WHILE_STATEMENT = 'DO_WHILE_STATEMENT';
var EMPTY_STATEMENT = 'EMPTY_STATEMENT';
var EXPORT_DECLARATION = 'EXPORT_DECLARATION';
var EXPORT_DEFAULT = 'EXPORT_DEFAULT';
var EXPORT_SPECIFIER = 'EXPORT_SPECIFIER';
var EXPORT_SPECIFIER_SET = 'EXPORT_SPECIFIER_SET';
var EXPORT_STAR = 'EXPORT_STAR';
var EXPRESSION_STATEMENT = 'EXPRESSION_STATEMENT';
var FINALLY = 'FINALLY';
var FOR_IN_STATEMENT = 'FOR_IN_STATEMENT';
var FOR_OF_STATEMENT = 'FOR_OF_STATEMENT';
var FOR_STATEMENT = 'FOR_STATEMENT';
var FORMAL_PARAMETER = 'FORMAL_PARAMETER';
var FORMAL_PARAMETER_LIST = 'FORMAL_PARAMETER_LIST';
var FUNCTION_BODY = 'FUNCTION_BODY';
var FUNCTION_DECLARATION = 'FUNCTION_DECLARATION';
var FUNCTION_EXPRESSION = 'FUNCTION_EXPRESSION';
var GENERATOR_COMPREHENSION = 'GENERATOR_COMPREHENSION';
var GET_ACCESSOR = 'GET_ACCESSOR';
var IDENTIFIER_EXPRESSION = 'IDENTIFIER_EXPRESSION';
var IF_STATEMENT = 'IF_STATEMENT';
var IMPORT_DECLARATION = 'IMPORT_DECLARATION';
var IMPORT_SPECIFIER = 'IMPORT_SPECIFIER';
var IMPORT_SPECIFIER_SET = 'IMPORT_SPECIFIER_SET';
var IMPORTED_BINDING = 'IMPORTED_BINDING';
var LABELLED_STATEMENT = 'LABELLED_STATEMENT';
var LITERAL_EXPRESSION = 'LITERAL_EXPRESSION';
var LITERAL_PROPERTY_NAME = 'LITERAL_PROPERTY_NAME';
var MEMBER_EXPRESSION = 'MEMBER_EXPRESSION';
var MEMBER_LOOKUP_EXPRESSION = 'MEMBER_LOOKUP_EXPRESSION';
var MODULE = 'MODULE';
var MODULE_DECLARATION = 'MODULE_DECLARATION';
var MODULE_SPECIFIER = 'MODULE_SPECIFIER';
var NAMED_EXPORT = 'NAMED_EXPORT';
var NEW_EXPRESSION = 'NEW_EXPRESSION';
var OBJECT_LITERAL_EXPRESSION = 'OBJECT_LITERAL_EXPRESSION';
var OBJECT_PATTERN = 'OBJECT_PATTERN';
var OBJECT_PATTERN_FIELD = 'OBJECT_PATTERN_FIELD';
var PAREN_EXPRESSION = 'PAREN_EXPRESSION';
var POSTFIX_EXPRESSION = 'POSTFIX_EXPRESSION';
var PREDEFINED_TYPE = 'PREDEFINED_TYPE';
var PROPERTY_METHOD_ASSIGNMENT = 'PROPERTY_METHOD_ASSIGNMENT';
var PROPERTY_NAME_ASSIGNMENT = 'PROPERTY_NAME_ASSIGNMENT';
var PROPERTY_NAME_SHORTHAND = 'PROPERTY_NAME_SHORTHAND';
var REST_PARAMETER = 'REST_PARAMETER';
var RETURN_STATEMENT = 'RETURN_STATEMENT';
var SCRIPT = 'SCRIPT';
var SET_ACCESSOR = 'SET_ACCESSOR';
var SPREAD_EXPRESSION = 'SPREAD_EXPRESSION';
var SPREAD_PATTERN_ELEMENT = 'SPREAD_PATTERN_ELEMENT';
var STATE_MACHINE = 'STATE_MACHINE';
var SUPER_EXPRESSION = 'SUPER_EXPRESSION';
var SWITCH_STATEMENT = 'SWITCH_STATEMENT';
var SYNTAX_ERROR_TREE = 'SYNTAX_ERROR_TREE';
var TEMPLATE_LITERAL_EXPRESSION = 'TEMPLATE_LITERAL_EXPRESSION';
var TEMPLATE_LITERAL_PORTION = 'TEMPLATE_LITERAL_PORTION';
var TEMPLATE_SUBSTITUTION = 'TEMPLATE_SUBSTITUTION';
var THIS_EXPRESSION = 'THIS_EXPRESSION';
var THROW_STATEMENT = 'THROW_STATEMENT';
var TRY_STATEMENT = 'TRY_STATEMENT';
var TYPE_NAME = 'TYPE_NAME';
var UNARY_EXPRESSION = 'UNARY_EXPRESSION';
var VARIABLE_DECLARATION = 'VARIABLE_DECLARATION';
var VARIABLE_DECLARATION_LIST = 'VARIABLE_DECLARATION_LIST';
var VARIABLE_STATEMENT = 'VARIABLE_STATEMENT';
var WHILE_STATEMENT = 'WHILE_STATEMENT';
var WITH_STATEMENT = 'WITH_STATEMENT';
var YIELD_EXPRESSION = 'YIELD_EXPRESSION';
return {
get ANNOTATION() {
return ANNOTATION;
},
get ANON_BLOCK() {
return ANON_BLOCK;
},
get ARGUMENT_LIST() {
return ARGUMENT_LIST;
},
get ARRAY_COMPREHENSION() {
return ARRAY_COMPREHENSION;
},
get ARRAY_LITERAL_EXPRESSION() {
return ARRAY_LITERAL_EXPRESSION;
},
get ARRAY_PATTERN() {
return ARRAY_PATTERN;
},
get ARROW_FUNCTION_EXPRESSION() {
return ARROW_FUNCTION_EXPRESSION;
},
get ASSIGNMENT_ELEMENT() {
return ASSIGNMENT_ELEMENT;
},
get AWAIT_EXPRESSION() {
return AWAIT_EXPRESSION;
},
get BINARY_EXPRESSION() {
return BINARY_EXPRESSION;
},
get BINDING_ELEMENT() {
return BINDING_ELEMENT;
},
get BINDING_IDENTIFIER() {
return BINDING_IDENTIFIER;
},
get BLOCK() {
return BLOCK;
},
get BREAK_STATEMENT() {
return BREAK_STATEMENT;
},
get CALL_EXPRESSION() {
return CALL_EXPRESSION;
},
get CASE_CLAUSE() {
return CASE_CLAUSE;
},
get CATCH() {
return CATCH;
},
get CLASS_DECLARATION() {
return CLASS_DECLARATION;
},
get CLASS_EXPRESSION() {
return CLASS_EXPRESSION;
},
get COMMA_EXPRESSION() {
return COMMA_EXPRESSION;
},
get COMPREHENSION_FOR() {
return COMPREHENSION_FOR;
},
get COMPREHENSION_IF() {
return COMPREHENSION_IF;
},
get COMPUTED_PROPERTY_NAME() {
return COMPUTED_PROPERTY_NAME;
},
get CONDITIONAL_EXPRESSION() {
return CONDITIONAL_EXPRESSION;
},
get CONTINUE_STATEMENT() {
return CONTINUE_STATEMENT;
},
get COVER_FORMALS() {
return COVER_FORMALS;
},
get COVER_INITIALIZED_NAME() {
return COVER_INITIALIZED_NAME;
},
get DEBUGGER_STATEMENT() {
return DEBUGGER_STATEMENT;
},
get DEFAULT_CLAUSE() {
return DEFAULT_CLAUSE;
},
get DO_WHILE_STATEMENT() {
return DO_WHILE_STATEMENT;
},
get EMPTY_STATEMENT() {
return EMPTY_STATEMENT;
},
get EXPORT_DECLARATION() {
return EXPORT_DECLARATION;
},
get EXPORT_DEFAULT() {
return EXPORT_DEFAULT;
},
get EXPORT_SPECIFIER() {
return EXPORT_SPECIFIER;
},
get EXPORT_SPECIFIER_SET() {
return EXPORT_SPECIFIER_SET;
},
get EXPORT_STAR() {
return EXPORT_STAR;
},
get EXPRESSION_STATEMENT() {
return EXPRESSION_STATEMENT;
},
get FINALLY() {
return FINALLY;
},
get FOR_IN_STATEMENT() {
return FOR_IN_STATEMENT;
},
get FOR_OF_STATEMENT() {
return FOR_OF_STATEMENT;
},
get FOR_STATEMENT() {
return FOR_STATEMENT;
},
get FORMAL_PARAMETER() {
return FORMAL_PARAMETER;
},
get FORMAL_PARAMETER_LIST() {
return FORMAL_PARAMETER_LIST;
},
get FUNCTION_BODY() {
return FUNCTION_BODY;
},
get FUNCTION_DECLARATION() {
return FUNCTION_DECLARATION;
},
get FUNCTION_EXPRESSION() {
return FUNCTION_EXPRESSION;
},
get GENERATOR_COMPREHENSION() {
return GENERATOR_COMPREHENSION;
},
get GET_ACCESSOR() {
return GET_ACCESSOR;
},
get IDENTIFIER_EXPRESSION() {
return IDENTIFIER_EXPRESSION;
},
get IF_STATEMENT() {
return IF_STATEMENT;
},
get IMPORT_DECLARATION() {
return IMPORT_DECLARATION;
},
get IMPORT_SPECIFIER() {
return IMPORT_SPECIFIER;
},
get IMPORT_SPECIFIER_SET() {
return IMPORT_SPECIFIER_SET;
},
get IMPORTED_BINDING() {
return IMPORTED_BINDING;
},
get LABELLED_STATEMENT() {
return LABELLED_STATEMENT;
},
get LITERAL_EXPRESSION() {
return LITERAL_EXPRESSION;
},
get LITERAL_PROPERTY_NAME() {
return LITERAL_PROPERTY_NAME;
},
get MEMBER_EXPRESSION() {
return MEMBER_EXPRESSION;
},
get MEMBER_LOOKUP_EXPRESSION() {
return MEMBER_LOOKUP_EXPRESSION;
},
get MODULE() {
return MODULE;
},
get MODULE_DECLARATION() {
return MODULE_DECLARATION;
},
get MODULE_SPECIFIER() {
return MODULE_SPECIFIER;
},
get NAMED_EXPORT() {
return NAMED_EXPORT;
},
get NEW_EXPRESSION() {
return NEW_EXPRESSION;
},
get OBJECT_LITERAL_EXPRESSION() {
return OBJECT_LITERAL_EXPRESSION;
},
get OBJECT_PATTERN() {
return OBJECT_PATTERN;
},
get OBJECT_PATTERN_FIELD() {
return OBJECT_PATTERN_FIELD;
},
get PAREN_EXPRESSION() {
return PAREN_EXPRESSION;
},
get POSTFIX_EXPRESSION() {
return POSTFIX_EXPRESSION;
},
get PREDEFINED_TYPE() {
return PREDEFINED_TYPE;
},
get PROPERTY_METHOD_ASSIGNMENT() {
return PROPERTY_METHOD_ASSIGNMENT;
},
get PROPERTY_NAME_ASSIGNMENT() {
return PROPERTY_NAME_ASSIGNMENT;
},
get PROPERTY_NAME_SHORTHAND() {
return PROPERTY_NAME_SHORTHAND;
},
get REST_PARAMETER() {
return REST_PARAMETER;
},
get RETURN_STATEMENT() {
return RETURN_STATEMENT;
},
get SCRIPT() {
return SCRIPT;
},
get SET_ACCESSOR() {
return SET_ACCESSOR;
},
get SPREAD_EXPRESSION() {
return SPREAD_EXPRESSION;
},
get SPREAD_PATTERN_ELEMENT() {
return SPREAD_PATTERN_ELEMENT;
},
get STATE_MACHINE() {
return STATE_MACHINE;
},
get SUPER_EXPRESSION() {
return SUPER_EXPRESSION;
},
get SWITCH_STATEMENT() {
return SWITCH_STATEMENT;
},
get SYNTAX_ERROR_TREE() {
return SYNTAX_ERROR_TREE;
},
get TEMPLATE_LITERAL_EXPRESSION() {
return TEMPLATE_LITERAL_EXPRESSION;
},
get TEMPLATE_LITERAL_PORTION() {
return TEMPLATE_LITERAL_PORTION;
},
get TEMPLATE_SUBSTITUTION() {
return TEMPLATE_SUBSTITUTION;
},
get THIS_EXPRESSION() {
return THIS_EXPRESSION;
},
get THROW_STATEMENT() {
return THROW_STATEMENT;
},
get TRY_STATEMENT() {
return TRY_STATEMENT;
},
get TYPE_NAME() {
return TYPE_NAME;
},
get UNARY_EXPRESSION() {
return UNARY_EXPRESSION;
},
get VARIABLE_DECLARATION() {
return VARIABLE_DECLARATION;
},
get VARIABLE_DECLARATION_LIST() {
return VARIABLE_DECLARATION_LIST;
},
get VARIABLE_STATEMENT() {
return VARIABLE_STATEMENT;
},
get WHILE_STATEMENT() {
return WHILE_STATEMENT;
},
get WITH_STATEMENT() {
return WITH_STATEMENT;
},
get YIELD_EXPRESSION() {
return YIELD_EXPRESSION;
}
};
});
System.register("traceur@0.0.52/src/syntax/ParseTreeVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/ParseTreeVisitor";
var ParseTreeVisitor = function ParseTreeVisitor() {};
($traceurRuntime.createClass)(ParseTreeVisitor, {
visitAny: function(tree) {
tree && tree.visit(this);
},
visit: function(tree) {
this.visitAny(tree);
},
visitList: function(list) {
if (list) {
for (var i = 0; i < list.length; i++) {
this.visitAny(list[i]);
}
}
},
visitStateMachine: function(tree) {
throw Error('State machines should not live outside of the GeneratorTransformer.');
},
visitAnnotation: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.args);
},
visitAnonBlock: function(tree) {
this.visitList(tree.statements);
},
visitArgumentList: function(tree) {
this.visitList(tree.args);
},
visitArrayComprehension: function(tree) {
this.visitList(tree.comprehensionList);
this.visitAny(tree.expression);
},
visitArrayLiteralExpression: function(tree) {
this.visitList(tree.elements);
},
visitArrayPattern: function(tree) {
this.visitList(tree.elements);
},
visitArrowFunctionExpression: function(tree) {
this.visitAny(tree.parameterList);
this.visitAny(tree.body);
},
visitAssignmentElement: function(tree) {
this.visitAny(tree.assignment);
this.visitAny(tree.initializer);
},
visitAwaitExpression: function(tree) {
this.visitAny(tree.expression);
},
visitBinaryExpression: function(tree) {
this.visitAny(tree.left);
this.visitAny(tree.right);
},
visitBindingElement: function(tree) {
this.visitAny(tree.binding);
this.visitAny(tree.initializer);
},
visitBindingIdentifier: function(tree) {},
visitBlock: function(tree) {
this.visitList(tree.statements);
},
visitBreakStatement: function(tree) {},
visitCallExpression: function(tree) {
this.visitAny(tree.operand);
this.visitAny(tree.args);
},
visitCaseClause: function(tree) {
this.visitAny(tree.expression);
this.visitList(tree.statements);
},
visitCatch: function(tree) {
this.visitAny(tree.binding);
this.visitAny(tree.catchBody);
},
visitClassDeclaration: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.superClass);
this.visitList(tree.elements);
this.visitList(tree.annotations);
},
visitClassExpression: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.superClass);
this.visitList(tree.elements);
this.visitList(tree.annotations);
},
visitCommaExpression: function(tree) {
this.visitList(tree.expressions);
},
visitComprehensionFor: function(tree) {
this.visitAny(tree.left);
this.visitAny(tree.iterator);
},
visitComprehensionIf: function(tree) {
this.visitAny(tree.expression);
},
visitComputedPropertyName: function(tree) {
this.visitAny(tree.expression);
},
visitConditionalExpression: function(tree) {
this.visitAny(tree.condition);
this.visitAny(tree.left);
this.visitAny(tree.right);
},
visitContinueStatement: function(tree) {},
visitCoverFormals: function(tree) {
this.visitList(tree.expressions);
},
visitCoverInitializedName: function(tree) {
this.visitAny(tree.initializer);
},
visitDebuggerStatement: function(tree) {},
visitDefaultClause: function(tree) {
this.visitList(tree.statements);
},
visitDoWhileStatement: function(tree) {
this.visitAny(tree.body);
this.visitAny(tree.condition);
},
visitEmptyStatement: function(tree) {},
visitExportDeclaration: function(tree) {
this.visitAny(tree.declaration);
this.visitList(tree.annotations);
},
visitExportDefault: function(tree) {
this.visitAny(tree.expression);
},
visitExportSpecifier: function(tree) {},
visitExportSpecifierSet: function(tree) {
this.visitList(tree.specifiers);
},
visitExportStar: function(tree) {},
visitExpressionStatement: function(tree) {
this.visitAny(tree.expression);
},
visitFinally: function(tree) {
this.visitAny(tree.block);
},
visitForInStatement: function(tree) {
this.visitAny(tree.initializer);
this.visitAny(tree.collection);
this.visitAny(tree.body);
},
visitForOfStatement: function(tree) {
this.visitAny(tree.initializer);
this.visitAny(tree.collection);
this.visitAny(tree.body);
},
visitForStatement: function(tree) {
this.visitAny(tree.initializer);
this.visitAny(tree.condition);
this.visitAny(tree.increment);
this.visitAny(tree.body);
},
visitFormalParameter: function(tree) {
this.visitAny(tree.parameter);
this.visitAny(tree.typeAnnotation);
this.visitList(tree.annotations);
},
visitFormalParameterList: function(tree) {
this.visitList(tree.parameters);
},
visitFunctionBody: function(tree) {
this.visitList(tree.statements);
},
visitFunctionDeclaration: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.parameterList);
this.visitAny(tree.typeAnnotation);
this.visitList(tree.annotations);
this.visitAny(tree.body);
},
visitFunctionExpression: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.parameterList);
this.visitAny(tree.typeAnnotation);
this.visitList(tree.annotations);
this.visitAny(tree.body);
},
visitGeneratorComprehension: function(tree) {
this.visitList(tree.comprehensionList);
this.visitAny(tree.expression);
},
visitGetAccessor: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.typeAnnotation);
this.visitList(tree.annotations);
this.visitAny(tree.body);
},
visitIdentifierExpression: function(tree) {},
visitIfStatement: function(tree) {
this.visitAny(tree.condition);
this.visitAny(tree.ifClause);
this.visitAny(tree.elseClause);
},
visitImportedBinding: function(tree) {
this.visitAny(tree.binding);
},
visitImportDeclaration: function(tree) {
this.visitAny(tree.importClause);
this.visitAny(tree.moduleSpecifier);
},
visitImportSpecifier: function(tree) {},
visitImportSpecifierSet: function(tree) {
this.visitList(tree.specifiers);
},
visitLabelledStatement: function(tree) {
this.visitAny(tree.statement);
},
visitLiteralExpression: function(tree) {},
visitLiteralPropertyName: function(tree) {},
visitMemberExpression: function(tree) {
this.visitAny(tree.operand);
},
visitMemberLookupExpression: function(tree) {
this.visitAny(tree.operand);
this.visitAny(tree.memberExpression);
},
visitModule: function(tree) {
this.visitList(tree.scriptItemList);
},
visitModuleDeclaration: function(tree) {
this.visitAny(tree.expression);
},
visitModuleSpecifier: function(tree) {},
visitNamedExport: function(tree) {
this.visitAny(tree.moduleSpecifier);
this.visitAny(tree.specifierSet);
},
visitNewExpression: function(tree) {
this.visitAny(tree.operand);
this.visitAny(tree.args);
},
visitObjectLiteralExpression: function(tree) {
this.visitList(tree.propertyNameAndValues);
},
visitObjectPattern: function(tree) {
this.visitList(tree.fields);
},
visitObjectPatternField: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.element);
},
visitParenExpression: function(tree) {
this.visitAny(tree.expression);
},
visitPostfixExpression: function(tree) {
this.visitAny(tree.operand);
},
visitPredefinedType: function(tree) {},
visitScript: function(tree) {
this.visitList(tree.scriptItemList);
},
visitPropertyMethodAssignment: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.parameterList);
this.visitAny(tree.typeAnnotation);
this.visitList(tree.annotations);
this.visitAny(tree.body);
},
visitPropertyNameAssignment: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.value);
},
visitPropertyNameShorthand: function(tree) {},
visitRestParameter: function(tree) {
this.visitAny(tree.identifier);
},
visitReturnStatement: function(tree) {
this.visitAny(tree.expression);
},
visitSetAccessor: function(tree) {
this.visitAny(tree.name);
this.visitAny(tree.parameterList);
this.visitList(tree.annotations);
this.visitAny(tree.body);
},
visitSpreadExpression: function(tree) {
this.visitAny(tree.expression);
},
visitSpreadPatternElement: function(tree) {
this.visitAny(tree.lvalue);
},
visitSuperExpression: function(tree) {},
visitSwitchStatement: function(tree) {
this.visitAny(tree.expression);
this.visitList(tree.caseClauses);
},
visitSyntaxErrorTree: function(tree) {},
visitTemplateLiteralExpression: function(tree) {
this.visitAny(tree.operand);
this.visitList(tree.elements);
},
visitTemplateLiteralPortion: function(tree) {},
visitTemplateSubstitution: function(tree) {
this.visitAny(tree.expression);
},
visitThisExpression: function(tree) {},
visitThrowStatement: function(tree) {
this.visitAny(tree.value);
},
visitTryStatement: function(tree) {
this.visitAny(tree.body);
this.visitAny(tree.catchBlock);
this.visitAny(tree.finallyBlock);
},
visitTypeName: function(tree) {
this.visitAny(tree.moduleName);
},
visitUnaryExpression: function(tree) {
this.visitAny(tree.operand);
},
visitVariableDeclaration: function(tree) {
this.visitAny(tree.lvalue);
this.visitAny(tree.typeAnnotation);
this.visitAny(tree.initializer);
},
visitVariableDeclarationList: function(tree) {
this.visitList(tree.declarations);
},
visitVariableStatement: function(tree) {
this.visitAny(tree.declarations);
},
visitWhileStatement: function(tree) {
this.visitAny(tree.condition);
this.visitAny(tree.body);
},
visitWithStatement: function(tree) {
this.visitAny(tree.expression);
this.visitAny(tree.body);
},
visitYieldExpression: function(tree) {
this.visitAny(tree.expression);
}
}, {});
return {get ParseTreeVisitor() {
return ParseTreeVisitor;
}};
});
System.register("traceur@0.0.52/src/syntax/Token", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/Token";
var $__45 = System.get("traceur@0.0.52/src/syntax/TokenType"),
AMPERSAND_EQUAL = $__45.AMPERSAND_EQUAL,
BAR_EQUAL = $__45.BAR_EQUAL,
CARET_EQUAL = $__45.CARET_EQUAL,
EQUAL = $__45.EQUAL,
LEFT_SHIFT_EQUAL = $__45.LEFT_SHIFT_EQUAL,
MINUS_EQUAL = $__45.MINUS_EQUAL,
PERCENT_EQUAL = $__45.PERCENT_EQUAL,
PLUS_EQUAL = $__45.PLUS_EQUAL,
RIGHT_SHIFT_EQUAL = $__45.RIGHT_SHIFT_EQUAL,
SLASH_EQUAL = $__45.SLASH_EQUAL,
STAR_EQUAL = $__45.STAR_EQUAL,
UNSIGNED_RIGHT_SHIFT_EQUAL = $__45.UNSIGNED_RIGHT_SHIFT_EQUAL;
var Token = function Token(type, location) {
this.type = type;
this.location = location;
};
($traceurRuntime.createClass)(Token, {
toString: function() {
return this.type;
},
isAssignmentOperator: function() {
return isAssignmentOperator(this.type);
},
isKeyword: function() {
return false;
},
isStrictKeyword: function() {
return false;
}
}, {});
function isAssignmentOperator(type) {
switch (type) {
case AMPERSAND_EQUAL:
case BAR_EQUAL:
case CARET_EQUAL:
case EQUAL:
case LEFT_SHIFT_EQUAL:
case MINUS_EQUAL:
case PERCENT_EQUAL:
case PLUS_EQUAL:
case RIGHT_SHIFT_EQUAL:
case SLASH_EQUAL:
case STAR_EQUAL:
case UNSIGNED_RIGHT_SHIFT_EQUAL:
return true;
}
return false;
}
return {
get Token() {
return Token;
},
get isAssignmentOperator() {
return isAssignmentOperator;
}
};
});
System.register("traceur@0.0.52/src/syntax/IdentifierToken", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/IdentifierToken";
var Token = System.get("traceur@0.0.52/src/syntax/Token").Token;
var IDENTIFIER = System.get("traceur@0.0.52/src/syntax/TokenType").IDENTIFIER;
var IdentifierToken = function IdentifierToken(location, value) {
this.location = location;
this.value = value;
};
($traceurRuntime.createClass)(IdentifierToken, {
toString: function() {
return this.value;
},
get type() {
return IDENTIFIER;
}
}, {}, Token);
return {get IdentifierToken() {
return IdentifierToken;
}};
});
System.register("traceur@0.0.52/src/util/JSON", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/JSON";
function transform(v) {
var replacer = arguments[1] !== (void 0) ? arguments[1] : (function(k, v) {
return v;
});
return transform_(replacer('', v), replacer);
}
function transform_(v, replacer) {
var rv,
tv;
if (Array.isArray(v)) {
var len = v.length;
rv = Array(len);
for (var i = 0; i < len; i++) {
tv = transform_(replacer(String(i), v[i]), replacer);
rv[i] = tv === undefined ? null : tv;
}
return rv;
}
if (v instanceof Object) {
rv = {};
Object.keys(v).forEach((function(k) {
tv = transform_(replacer(k, v[k]), replacer);
if (tv !== undefined) {
rv[k] = tv;
}
}));
return rv;
}
return v;
}
return {get transform() {
return transform;
}};
});
System.register("traceur@0.0.52/src/syntax/PredefinedName", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/PredefinedName";
var $ARGUMENTS = '$arguments';
var ANY = 'any';
var APPLY = 'apply';
var ARGUMENTS = 'arguments';
var ARRAY = 'Array';
var AS = 'as';
var ASYNC = 'async';
var AWAIT = 'await';
var BIND = 'bind';
var CALL = 'call';
var CONFIGURABLE = 'configurable';
var CONSTRUCTOR = 'constructor';
var CREATE = 'create';
var CURRENT = 'current';
var DEFINE_PROPERTY = 'defineProperty';
var ENUMERABLE = 'enumerable';
var FREEZE = 'freeze';
var FROM = 'from';
var FUNCTION = 'Function';
var GET = 'get';
var HAS = 'has';
var LENGTH = 'length';
var MODULE = 'module';
var NEW = 'new';
var OBJECT = 'Object';
var OBJECT_NAME = 'Object';
var OF = 'of';
var PREVENT_EXTENSIONS = 'preventExtensions';
var PROTOTYPE = 'prototype';
var PUSH = 'push';
var SET = 'set';
var SLICE = 'slice';
var THIS = 'this';
var TRACEUR_RUNTIME = '$traceurRuntime';
var UNDEFINED = 'undefined';
var WRITABLE = 'writable';
return {
get $ARGUMENTS() {
return $ARGUMENTS;
},
get ANY() {
return ANY;
},
get APPLY() {
return APPLY;
},
get ARGUMENTS() {
return ARGUMENTS;
},
get ARRAY() {
return ARRAY;
},
get AS() {
return AS;
},
get ASYNC() {
return ASYNC;
},
get AWAIT() {
return AWAIT;
},
get BIND() {
return BIND;
},
get CALL() {
return CALL;
},
get CONFIGURABLE() {
return CONFIGURABLE;
},
get CONSTRUCTOR() {
return CONSTRUCTOR;
},
get CREATE() {
return CREATE;
},
get CURRENT() {
return CURRENT;
},
get DEFINE_PROPERTY() {
return DEFINE_PROPERTY;
},
get ENUMERABLE() {
return ENUMERABLE;
},
get FREEZE() {
return FREEZE;
},
get FROM() {
return FROM;
},
get FUNCTION() {
return FUNCTION;
},
get GET() {
return GET;
},
get HAS() {
return HAS;
},
get LENGTH() {
return LENGTH;
},
get MODULE() {
return MODULE;
},
get NEW() {
return NEW;
},
get OBJECT() {
return OBJECT;
},
get OBJECT_NAME() {
return OBJECT_NAME;
},
get OF() {
return OF;
},
get PREVENT_EXTENSIONS() {
return PREVENT_EXTENSIONS;
},
get PROTOTYPE() {
return PROTOTYPE;
},
get PUSH() {
return PUSH;
},
get SET() {
return SET;
},
get SLICE() {
return SLICE;
},
get THIS() {
return THIS;
},
get TRACEUR_RUNTIME() {
return TRACEUR_RUNTIME;
},
get UNDEFINED() {
return UNDEFINED;
},
get WRITABLE() {
return WRITABLE;
}
};
});
System.register("traceur@0.0.52/src/syntax/trees/ParseTree", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/trees/ParseTree";
var ParseTreeType = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType");
var $__50 = System.get("traceur@0.0.52/src/syntax/TokenType"),
IDENTIFIER = $__50.IDENTIFIER,
STAR = $__50.STAR,
STRING = $__50.STRING,
VAR = $__50.VAR;
var Token = System.get("traceur@0.0.52/src/syntax/Token").Token;
var utilJSON = System.get("traceur@0.0.52/src/util/JSON");
var ASYNC = System.get("traceur@0.0.52/src/syntax/PredefinedName").ASYNC;
var $__53 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
ARRAY_COMPREHENSION = $__53.ARRAY_COMPREHENSION,
ARRAY_LITERAL_EXPRESSION = $__53.ARRAY_LITERAL_EXPRESSION,
ARRAY_PATTERN = $__53.ARRAY_PATTERN,
ARROW_FUNCTION_EXPRESSION = $__53.ARROW_FUNCTION_EXPRESSION,
AWAIT_EXPRESSION = $__53.AWAIT_EXPRESSION,
BINARY_EXPRESSION = $__53.BINARY_EXPRESSION,
BLOCK = $__53.BLOCK,
BREAK_STATEMENT = $__53.BREAK_STATEMENT,
CALL_EXPRESSION = $__53.CALL_EXPRESSION,
CLASS_DECLARATION = $__53.CLASS_DECLARATION,
CLASS_EXPRESSION = $__53.CLASS_EXPRESSION,
COMMA_EXPRESSION = $__53.COMMA_EXPRESSION,
CONDITIONAL_EXPRESSION = $__53.CONDITIONAL_EXPRESSION,
CONTINUE_STATEMENT = $__53.CONTINUE_STATEMENT,
DEBUGGER_STATEMENT = $__53.DEBUGGER_STATEMENT,
DO_WHILE_STATEMENT = $__53.DO_WHILE_STATEMENT,
EMPTY_STATEMENT = $__53.EMPTY_STATEMENT,
EXPORT_DECLARATION = $__53.EXPORT_DECLARATION,
EXPRESSION_STATEMENT = $__53.EXPRESSION_STATEMENT,
FOR_IN_STATEMENT = $__53.FOR_IN_STATEMENT,
FOR_OF_STATEMENT = $__53.FOR_OF_STATEMENT,
FOR_STATEMENT = $__53.FOR_STATEMENT,
FORMAL_PARAMETER = $__53.FORMAL_PARAMETER,
FUNCTION_DECLARATION = $__53.FUNCTION_DECLARATION,
FUNCTION_EXPRESSION = $__53.FUNCTION_EXPRESSION,
GENERATOR_COMPREHENSION = $__53.GENERATOR_COMPREHENSION,
IDENTIFIER_EXPRESSION = $__53.IDENTIFIER_EXPRESSION,
IF_STATEMENT = $__53.IF_STATEMENT,
IMPORT_DECLARATION = $__53.IMPORT_DECLARATION,
LABELLED_STATEMENT = $__53.LABELLED_STATEMENT,
LITERAL_EXPRESSION = $__53.LITERAL_EXPRESSION,
MEMBER_EXPRESSION = $__53.MEMBER_EXPRESSION,
MEMBER_LOOKUP_EXPRESSION = $__53.MEMBER_LOOKUP_EXPRESSION,
MODULE_DECLARATION = $__53.MODULE_DECLARATION,
NEW_EXPRESSION = $__53.NEW_EXPRESSION,
OBJECT_LITERAL_EXPRESSION = $__53.OBJECT_LITERAL_EXPRESSION,
OBJECT_PATTERN = $__53.OBJECT_PATTERN,
PAREN_EXPRESSION = $__53.PAREN_EXPRESSION,
POSTFIX_EXPRESSION = $__53.POSTFIX_EXPRESSION,
REST_PARAMETER = $__53.REST_PARAMETER,
RETURN_STATEMENT = $__53.RETURN_STATEMENT,
SPREAD_EXPRESSION = $__53.SPREAD_EXPRESSION,
SPREAD_PATTERN_ELEMENT = $__53.SPREAD_PATTERN_ELEMENT,
SUPER_EXPRESSION = $__53.SUPER_EXPRESSION,
SWITCH_STATEMENT = $__53.SWITCH_STATEMENT,
TEMPLATE_LITERAL_EXPRESSION = $__53.TEMPLATE_LITERAL_EXPRESSION,
THIS_EXPRESSION = $__53.THIS_EXPRESSION,
THROW_STATEMENT = $__53.THROW_STATEMENT,
TRY_STATEMENT = $__53.TRY_STATEMENT,
UNARY_EXPRESSION = $__53.UNARY_EXPRESSION,
VARIABLE_DECLARATION = $__53.VARIABLE_DECLARATION,
VARIABLE_STATEMENT = $__53.VARIABLE_STATEMENT,
WHILE_STATEMENT = $__53.WHILE_STATEMENT,
WITH_STATEMENT = $__53.WITH_STATEMENT,
YIELD_EXPRESSION = $__53.YIELD_EXPRESSION;
;
var ParseTree = function ParseTree(type, location) {
throw new Error("Don't use for now. 'super' is currently very slow.");
this.type = type;
this.location = location;
};
var $ParseTree = ParseTree;
($traceurRuntime.createClass)(ParseTree, {
isPattern: function() {
switch (this.type) {
case ARRAY_PATTERN:
case OBJECT_PATTERN:
return true;
default:
return false;
}
},
isLeftHandSideExpression: function() {
switch (this.type) {
case THIS_EXPRESSION:
case CLASS_EXPRESSION:
case SUPER_EXPRESSION:
case IDENTIFIER_EXPRESSION:
case LITERAL_EXPRESSION:
case ARRAY_LITERAL_EXPRESSION:
case OBJECT_LITERAL_EXPRESSION:
case NEW_EXPRESSION:
case MEMBER_EXPRESSION:
case MEMBER_LOOKUP_EXPRESSION:
case CALL_EXPRESSION:
case FUNCTION_EXPRESSION:
case TEMPLATE_LITERAL_EXPRESSION:
return true;
case PAREN_EXPRESSION:
return this.expression.isLeftHandSideExpression();
default:
return false;
}
},
isAssignmentExpression: function() {
switch (this.type) {
case ARRAY_COMPREHENSION:
case ARRAY_LITERAL_EXPRESSION:
case ARROW_FUNCTION_EXPRESSION:
case AWAIT_EXPRESSION:
case BINARY_EXPRESSION:
case CALL_EXPRESSION:
case CLASS_EXPRESSION:
case CONDITIONAL_EXPRESSION:
case FUNCTION_EXPRESSION:
case GENERATOR_COMPREHENSION:
case IDENTIFIER_EXPRESSION:
case LITERAL_EXPRESSION:
case MEMBER_EXPRESSION:
case MEMBER_LOOKUP_EXPRESSION:
case NEW_EXPRESSION:
case OBJECT_LITERAL_EXPRESSION:
case PAREN_EXPRESSION:
case POSTFIX_EXPRESSION:
case TEMPLATE_LITERAL_EXPRESSION:
case SUPER_EXPRESSION:
case THIS_EXPRESSION:
case UNARY_EXPRESSION:
case YIELD_EXPRESSION:
return true;
default:
return false;
}
},
isMemberExpression: function() {
switch (this.type) {
case THIS_EXPRESSION:
case CLASS_EXPRESSION:
case SUPER_EXPRESSION:
case IDENTIFIER_EXPRESSION:
case LITERAL_EXPRESSION:
case ARRAY_LITERAL_EXPRESSION:
case OBJECT_LITERAL_EXPRESSION:
case PAREN_EXPRESSION:
case TEMPLATE_LITERAL_EXPRESSION:
case FUNCTION_EXPRESSION:
case MEMBER_LOOKUP_EXPRESSION:
case MEMBER_EXPRESSION:
case CALL_EXPRESSION:
return true;
case NEW_EXPRESSION:
return this.args != null;
}
return false;
},
isExpression: function() {
return this.isAssignmentExpression() || this.type == COMMA_EXPRESSION;
},
isAssignmentOrSpread: function() {
return this.isAssignmentExpression() || this.type == SPREAD_EXPRESSION;
},
isRestParameter: function() {
return this.type == REST_PARAMETER || (this.type == FORMAL_PARAMETER && this.parameter.isRestParameter());
},
isSpreadPatternElement: function() {
return this.type == SPREAD_PATTERN_ELEMENT;
},
isStatementListItem: function() {
return this.isStatement() || this.isDeclaration();
},
isStatement: function() {
switch (this.type) {
case BLOCK:
case VARIABLE_STATEMENT:
case EMPTY_STATEMENT:
case EXPRESSION_STATEMENT:
case IF_STATEMENT:
case CONTINUE_STATEMENT:
case BREAK_STATEMENT:
case RETURN_STATEMENT:
case WITH_STATEMENT:
case LABELLED_STATEMENT:
case THROW_STATEMENT:
case TRY_STATEMENT:
case DEBUGGER_STATEMENT:
return true;
}
return this.isBreakableStatement();
},
isDeclaration: function() {
switch (this.type) {
case FUNCTION_DECLARATION:
case CLASS_DECLARATION:
return true;
}
return this.isLexicalDeclaration();
},
isLexicalDeclaration: function() {
switch (this.type) {
case VARIABLE_STATEMENT:
return this.declarations.declarationType !== VAR;
}
return false;
},
isBreakableStatement: function() {
switch (this.type) {
case SWITCH_STATEMENT:
return true;
}
return this.isIterationStatement();
},
isIterationStatement: function() {
switch (this.type) {
case DO_WHILE_STATEMENT:
case FOR_IN_STATEMENT:
case FOR_OF_STATEMENT:
case FOR_STATEMENT:
case WHILE_STATEMENT:
return true;
}
return false;
},
isScriptElement: function() {
switch (this.type) {
case CLASS_DECLARATION:
case EXPORT_DECLARATION:
case FUNCTION_DECLARATION:
case IMPORT_DECLARATION:
case MODULE_DECLARATION:
case VARIABLE_DECLARATION:
return true;
}
return this.isStatement();
},
isGenerator: function() {
return this.functionKind !== null && this.functionKind.type === STAR;
},
isAsyncFunction: function() {
return this.functionKind !== null && this.functionKind.type === IDENTIFIER && this.functionKind.value === ASYNC;
},
getDirectivePrologueStringToken_: function() {
var tree = this;
if (tree.type !== EXPRESSION_STATEMENT || !(tree = tree.expression))
return null;
if (tree.type !== LITERAL_EXPRESSION || !(tree = tree.literalToken))
return null;
if (tree.type !== STRING)
return null;
return tree;
},
isDirectivePrologue: function() {
return this.getDirectivePrologueStringToken_() !== null;
},
isUseStrictDirective: function() {
var token = this.getDirectivePrologueStringToken_();
if (!token)
return false;
var v = token.value;
return v === '"use strict"' || v === "'use strict'";
},
toJSON: function() {
return utilJSON.transform(this, $ParseTree.replacer);
},
stringify: function() {
var indent = arguments[0] !== (void 0) ? arguments[0] : 2;
return JSON.stringify(this, $ParseTree.replacer, indent);
}
}, {
stripLocation: function(key, value) {
if (key === 'location') {
return undefined;
}
return value;
},
replacer: function(k, v) {
if (v instanceof $ParseTree || v instanceof Token) {
var rv = {type: v.type};
Object.keys(v).forEach(function(name) {
if (name !== 'location')
rv[name] = v[name];
});
return rv;
}
return v;
}
});
return {
get ParseTreeType() {
return ParseTreeType;
},
get ParseTree() {
return ParseTree;
}
};
});
System.register("traceur@0.0.52/src/syntax/trees/ParseTrees", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/trees/ParseTrees";
var ParseTree = System.get("traceur@0.0.52/src/syntax/trees/ParseTree").ParseTree;
var ParseTreeType = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType");
var ANNOTATION = ParseTreeType.ANNOTATION;
var Annotation = function Annotation(location, name, args) {
this.location = location;
this.name = name;
this.args = args;
};
($traceurRuntime.createClass)(Annotation, {
transform: function(transformer) {
return transformer.transformAnnotation(this);
},
visit: function(visitor) {
visitor.visitAnnotation(this);
},
get type() {
return ANNOTATION;
}
}, {}, ParseTree);
var ANON_BLOCK = ParseTreeType.ANON_BLOCK;
var AnonBlock = function AnonBlock(location, statements) {
this.location = location;
this.statements = statements;
};
($traceurRuntime.createClass)(AnonBlock, {
transform: function(transformer) {
return transformer.transformAnonBlock(this);
},
visit: function(visitor) {
visitor.visitAnonBlock(this);
},
get type() {
return ANON_BLOCK;
}
}, {}, ParseTree);
var ARGUMENT_LIST = ParseTreeType.ARGUMENT_LIST;
var ArgumentList = function ArgumentList(location, args) {
this.location = location;
this.args = args;
};
($traceurRuntime.createClass)(ArgumentList, {
transform: function(transformer) {
return transformer.transformArgumentList(this);
},
visit: function(visitor) {
visitor.visitArgumentList(this);
},
get type() {
return ARGUMENT_LIST;
}
}, {}, ParseTree);
var ARRAY_COMPREHENSION = ParseTreeType.ARRAY_COMPREHENSION;
var ArrayComprehension = function ArrayComprehension(location, comprehensionList, expression) {
this.location = location;
this.comprehensionList = comprehensionList;
this.expression = expression;
};
($traceurRuntime.createClass)(ArrayComprehension, {
transform: function(transformer) {
return transformer.transformArrayComprehension(this);
},
visit: function(visitor) {
visitor.visitArrayComprehension(this);
},
get type() {
return ARRAY_COMPREHENSION;
}
}, {}, ParseTree);
var ARRAY_LITERAL_EXPRESSION = ParseTreeType.ARRAY_LITERAL_EXPRESSION;
var ArrayLiteralExpression = function ArrayLiteralExpression(location, elements) {
this.location = location;
this.elements = elements;
};
($traceurRuntime.createClass)(ArrayLiteralExpression, {
transform: function(transformer) {
return transformer.transformArrayLiteralExpression(this);
},
visit: function(visitor) {
visitor.visitArrayLiteralExpression(this);
},
get type() {
return ARRAY_LITERAL_EXPRESSION;
}
}, {}, ParseTree);
var ARRAY_PATTERN = ParseTreeType.ARRAY_PATTERN;
var ArrayPattern = function ArrayPattern(location, elements) {
this.location = location;
this.elements = elements;
};
($traceurRuntime.createClass)(ArrayPattern, {
transform: function(transformer) {
return transformer.transformArrayPattern(this);
},
visit: function(visitor) {
visitor.visitArrayPattern(this);
},
get type() {
return ARRAY_PATTERN;
}
}, {}, ParseTree);
var ARROW_FUNCTION_EXPRESSION = ParseTreeType.ARROW_FUNCTION_EXPRESSION;
var ArrowFunctionExpression = function ArrowFunctionExpression(location, functionKind, parameterList, body) {
this.location = location;
this.functionKind = functionKind;
this.parameterList = parameterList;
this.body = body;
};
($traceurRuntime.createClass)(ArrowFunctionExpression, {
transform: function(transformer) {
return transformer.transformArrowFunctionExpression(this);
},
visit: function(visitor) {
visitor.visitArrowFunctionExpression(this);
},
get type() {
return ARROW_FUNCTION_EXPRESSION;
}
}, {}, ParseTree);
var ASSIGNMENT_ELEMENT = ParseTreeType.ASSIGNMENT_ELEMENT;
var AssignmentElement = function AssignmentElement(location, assignment, initializer) {
this.location = location;
this.assignment = assignment;
this.initializer = initializer;
};
($traceurRuntime.createClass)(AssignmentElement, {
transform: function(transformer) {
return transformer.transformAssignmentElement(this);
},
visit: function(visitor) {
visitor.visitAssignmentElement(this);
},
get type() {
return ASSIGNMENT_ELEMENT;
}
}, {}, ParseTree);
var AWAIT_EXPRESSION = ParseTreeType.AWAIT_EXPRESSION;
var AwaitExpression = function AwaitExpression(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(AwaitExpression, {
transform: function(transformer) {
return transformer.transformAwaitExpression(this);
},
visit: function(visitor) {
visitor.visitAwaitExpression(this);
},
get type() {
return AWAIT_EXPRESSION;
}
}, {}, ParseTree);
var BINARY_EXPRESSION = ParseTreeType.BINARY_EXPRESSION;
var BinaryExpression = function BinaryExpression(location, left, operator, right) {
this.location = location;
this.left = left;
this.operator = operator;
this.right = right;
};
($traceurRuntime.createClass)(BinaryExpression, {
transform: function(transformer) {
return transformer.transformBinaryExpression(this);
},
visit: function(visitor) {
visitor.visitBinaryExpression(this);
},
get type() {
return BINARY_EXPRESSION;
}
}, {}, ParseTree);
var BINDING_ELEMENT = ParseTreeType.BINDING_ELEMENT;
var BindingElement = function BindingElement(location, binding, initializer) {
this.location = location;
this.binding = binding;
this.initializer = initializer;
};
($traceurRuntime.createClass)(BindingElement, {
transform: function(transformer) {
return transformer.transformBindingElement(this);
},
visit: function(visitor) {
visitor.visitBindingElement(this);
},
get type() {
return BINDING_ELEMENT;
}
}, {}, ParseTree);
var BINDING_IDENTIFIER = ParseTreeType.BINDING_IDENTIFIER;
var BindingIdentifier = function BindingIdentifier(location, identifierToken) {
this.location = location;
this.identifierToken = identifierToken;
};
($traceurRuntime.createClass)(BindingIdentifier, {
transform: function(transformer) {
return transformer.transformBindingIdentifier(this);
},
visit: function(visitor) {
visitor.visitBindingIdentifier(this);
},
get type() {
return BINDING_IDENTIFIER;
}
}, {}, ParseTree);
var BLOCK = ParseTreeType.BLOCK;
var Block = function Block(location, statements) {
this.location = location;
this.statements = statements;
};
($traceurRuntime.createClass)(Block, {
transform: function(transformer) {
return transformer.transformBlock(this);
},
visit: function(visitor) {
visitor.visitBlock(this);
},
get type() {
return BLOCK;
}
}, {}, ParseTree);
var BREAK_STATEMENT = ParseTreeType.BREAK_STATEMENT;
var BreakStatement = function BreakStatement(location, name) {
this.location = location;
this.name = name;
};
($traceurRuntime.createClass)(BreakStatement, {
transform: function(transformer) {
return transformer.transformBreakStatement(this);
},
visit: function(visitor) {
visitor.visitBreakStatement(this);
},
get type() {
return BREAK_STATEMENT;
}
}, {}, ParseTree);
var CALL_EXPRESSION = ParseTreeType.CALL_EXPRESSION;
var CallExpression = function CallExpression(location, operand, args) {
this.location = location;
this.operand = operand;
this.args = args;
};
($traceurRuntime.createClass)(CallExpression, {
transform: function(transformer) {
return transformer.transformCallExpression(this);
},
visit: function(visitor) {
visitor.visitCallExpression(this);
},
get type() {
return CALL_EXPRESSION;
}
}, {}, ParseTree);
var CASE_CLAUSE = ParseTreeType.CASE_CLAUSE;
var CaseClause = function CaseClause(location, expression, statements) {
this.location = location;
this.expression = expression;
this.statements = statements;
};
($traceurRuntime.createClass)(CaseClause, {
transform: function(transformer) {
return transformer.transformCaseClause(this);
},
visit: function(visitor) {
visitor.visitCaseClause(this);
},
get type() {
return CASE_CLAUSE;
}
}, {}, ParseTree);
var CATCH = ParseTreeType.CATCH;
var Catch = function Catch(location, binding, catchBody) {
this.location = location;
this.binding = binding;
this.catchBody = catchBody;
};
($traceurRuntime.createClass)(Catch, {
transform: function(transformer) {
return transformer.transformCatch(this);
},
visit: function(visitor) {
visitor.visitCatch(this);
},
get type() {
return CATCH;
}
}, {}, ParseTree);
var CLASS_DECLARATION = ParseTreeType.CLASS_DECLARATION;
var ClassDeclaration = function ClassDeclaration(location, name, superClass, elements, annotations) {
this.location = location;
this.name = name;
this.superClass = superClass;
this.elements = elements;
this.annotations = annotations;
};
($traceurRuntime.createClass)(ClassDeclaration, {
transform: function(transformer) {
return transformer.transformClassDeclaration(this);
},
visit: function(visitor) {
visitor.visitClassDeclaration(this);
},
get type() {
return CLASS_DECLARATION;
}
}, {}, ParseTree);
var CLASS_EXPRESSION = ParseTreeType.CLASS_EXPRESSION;
var ClassExpression = function ClassExpression(location, name, superClass, elements, annotations) {
this.location = location;
this.name = name;
this.superClass = superClass;
this.elements = elements;
this.annotations = annotations;
};
($traceurRuntime.createClass)(ClassExpression, {
transform: function(transformer) {
return transformer.transformClassExpression(this);
},
visit: function(visitor) {
visitor.visitClassExpression(this);
},
get type() {
return CLASS_EXPRESSION;
}
}, {}, ParseTree);
var COMMA_EXPRESSION = ParseTreeType.COMMA_EXPRESSION;
var CommaExpression = function CommaExpression(location, expressions) {
this.location = location;
this.expressions = expressions;
};
($traceurRuntime.createClass)(CommaExpression, {
transform: function(transformer) {
return transformer.transformCommaExpression(this);
},
visit: function(visitor) {
visitor.visitCommaExpression(this);
},
get type() {
return COMMA_EXPRESSION;
}
}, {}, ParseTree);
var COMPREHENSION_FOR = ParseTreeType.COMPREHENSION_FOR;
var ComprehensionFor = function ComprehensionFor(location, left, iterator) {
this.location = location;
this.left = left;
this.iterator = iterator;
};
($traceurRuntime.createClass)(ComprehensionFor, {
transform: function(transformer) {
return transformer.transformComprehensionFor(this);
},
visit: function(visitor) {
visitor.visitComprehensionFor(this);
},
get type() {
return COMPREHENSION_FOR;
}
}, {}, ParseTree);
var COMPREHENSION_IF = ParseTreeType.COMPREHENSION_IF;
var ComprehensionIf = function ComprehensionIf(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(ComprehensionIf, {
transform: function(transformer) {
return transformer.transformComprehensionIf(this);
},
visit: function(visitor) {
visitor.visitComprehensionIf(this);
},
get type() {
return COMPREHENSION_IF;
}
}, {}, ParseTree);
var COMPUTED_PROPERTY_NAME = ParseTreeType.COMPUTED_PROPERTY_NAME;
var ComputedPropertyName = function ComputedPropertyName(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(ComputedPropertyName, {
transform: function(transformer) {
return transformer.transformComputedPropertyName(this);
},
visit: function(visitor) {
visitor.visitComputedPropertyName(this);
},
get type() {
return COMPUTED_PROPERTY_NAME;
}
}, {}, ParseTree);
var CONDITIONAL_EXPRESSION = ParseTreeType.CONDITIONAL_EXPRESSION;
var ConditionalExpression = function ConditionalExpression(location, condition, left, right) {
this.location = location;
this.condition = condition;
this.left = left;
this.right = right;
};
($traceurRuntime.createClass)(ConditionalExpression, {
transform: function(transformer) {
return transformer.transformConditionalExpression(this);
},
visit: function(visitor) {
visitor.visitConditionalExpression(this);
},
get type() {
return CONDITIONAL_EXPRESSION;
}
}, {}, ParseTree);
var CONTINUE_STATEMENT = ParseTreeType.CONTINUE_STATEMENT;
var ContinueStatement = function ContinueStatement(location, name) {
this.location = location;
this.name = name;
};
($traceurRuntime.createClass)(ContinueStatement, {
transform: function(transformer) {
return transformer.transformContinueStatement(this);
},
visit: function(visitor) {
visitor.visitContinueStatement(this);
},
get type() {
return CONTINUE_STATEMENT;
}
}, {}, ParseTree);
var COVER_FORMALS = ParseTreeType.COVER_FORMALS;
var CoverFormals = function CoverFormals(location, expressions) {
this.location = location;
this.expressions = expressions;
};
($traceurRuntime.createClass)(CoverFormals, {
transform: function(transformer) {
return transformer.transformCoverFormals(this);
},
visit: function(visitor) {
visitor.visitCoverFormals(this);
},
get type() {
return COVER_FORMALS;
}
}, {}, ParseTree);
var COVER_INITIALIZED_NAME = ParseTreeType.COVER_INITIALIZED_NAME;
var CoverInitializedName = function CoverInitializedName(location, name, equalToken, initializer) {
this.location = location;
this.name = name;
this.equalToken = equalToken;
this.initializer = initializer;
};
($traceurRuntime.createClass)(CoverInitializedName, {
transform: function(transformer) {
return transformer.transformCoverInitializedName(this);
},
visit: function(visitor) {
visitor.visitCoverInitializedName(this);
},
get type() {
return COVER_INITIALIZED_NAME;
}
}, {}, ParseTree);
var DEBUGGER_STATEMENT = ParseTreeType.DEBUGGER_STATEMENT;
var DebuggerStatement = function DebuggerStatement(location) {
this.location = location;
};
($traceurRuntime.createClass)(DebuggerStatement, {
transform: function(transformer) {
return transformer.transformDebuggerStatement(this);
},
visit: function(visitor) {
visitor.visitDebuggerStatement(this);
},
get type() {
return DEBUGGER_STATEMENT;
}
}, {}, ParseTree);
var DEFAULT_CLAUSE = ParseTreeType.DEFAULT_CLAUSE;
var DefaultClause = function DefaultClause(location, statements) {
this.location = location;
this.statements = statements;
};
($traceurRuntime.createClass)(DefaultClause, {
transform: function(transformer) {
return transformer.transformDefaultClause(this);
},
visit: function(visitor) {
visitor.visitDefaultClause(this);
},
get type() {
return DEFAULT_CLAUSE;
}
}, {}, ParseTree);
var DO_WHILE_STATEMENT = ParseTreeType.DO_WHILE_STATEMENT;
var DoWhileStatement = function DoWhileStatement(location, body, condition) {
this.location = location;
this.body = body;
this.condition = condition;
};
($traceurRuntime.createClass)(DoWhileStatement, {
transform: function(transformer) {
return transformer.transformDoWhileStatement(this);
},
visit: function(visitor) {
visitor.visitDoWhileStatement(this);
},
get type() {
return DO_WHILE_STATEMENT;
}
}, {}, ParseTree);
var EMPTY_STATEMENT = ParseTreeType.EMPTY_STATEMENT;
var EmptyStatement = function EmptyStatement(location) {
this.location = location;
};
($traceurRuntime.createClass)(EmptyStatement, {
transform: function(transformer) {
return transformer.transformEmptyStatement(this);
},
visit: function(visitor) {
visitor.visitEmptyStatement(this);
},
get type() {
return EMPTY_STATEMENT;
}
}, {}, ParseTree);
var EXPORT_DECLARATION = ParseTreeType.EXPORT_DECLARATION;
var ExportDeclaration = function ExportDeclaration(location, declaration, annotations) {
this.location = location;
this.declaration = declaration;
this.annotations = annotations;
};
($traceurRuntime.createClass)(ExportDeclaration, {
transform: function(transformer) {
return transformer.transformExportDeclaration(this);
},
visit: function(visitor) {
visitor.visitExportDeclaration(this);
},
get type() {
return EXPORT_DECLARATION;
}
}, {}, ParseTree);
var EXPORT_DEFAULT = ParseTreeType.EXPORT_DEFAULT;
var ExportDefault = function ExportDefault(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(ExportDefault, {
transform: function(transformer) {
return transformer.transformExportDefault(this);
},
visit: function(visitor) {
visitor.visitExportDefault(this);
},
get type() {
return EXPORT_DEFAULT;
}
}, {}, ParseTree);
var EXPORT_SPECIFIER = ParseTreeType.EXPORT_SPECIFIER;
var ExportSpecifier = function ExportSpecifier(location, lhs, rhs) {
this.location = location;
this.lhs = lhs;
this.rhs = rhs;
};
($traceurRuntime.createClass)(ExportSpecifier, {
transform: function(transformer) {
return transformer.transformExportSpecifier(this);
},
visit: function(visitor) {
visitor.visitExportSpecifier(this);
},
get type() {
return EXPORT_SPECIFIER;
}
}, {}, ParseTree);
var EXPORT_SPECIFIER_SET = ParseTreeType.EXPORT_SPECIFIER_SET;
var ExportSpecifierSet = function ExportSpecifierSet(location, specifiers) {
this.location = location;
this.specifiers = specifiers;
};
($traceurRuntime.createClass)(ExportSpecifierSet, {
transform: function(transformer) {
return transformer.transformExportSpecifierSet(this);
},
visit: function(visitor) {
visitor.visitExportSpecifierSet(this);
},
get type() {
return EXPORT_SPECIFIER_SET;
}
}, {}, ParseTree);
var EXPORT_STAR = ParseTreeType.EXPORT_STAR;
var ExportStar = function ExportStar(location) {
this.location = location;
};
($traceurRuntime.createClass)(ExportStar, {
transform: function(transformer) {
return transformer.transformExportStar(this);
},
visit: function(visitor) {
visitor.visitExportStar(this);
},
get type() {
return EXPORT_STAR;
}
}, {}, ParseTree);
var EXPRESSION_STATEMENT = ParseTreeType.EXPRESSION_STATEMENT;
var ExpressionStatement = function ExpressionStatement(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(ExpressionStatement, {
transform: function(transformer) {
return transformer.transformExpressionStatement(this);
},
visit: function(visitor) {
visitor.visitExpressionStatement(this);
},
get type() {
return EXPRESSION_STATEMENT;
}
}, {}, ParseTree);
var FINALLY = ParseTreeType.FINALLY;
var Finally = function Finally(location, block) {
this.location = location;
this.block = block;
};
($traceurRuntime.createClass)(Finally, {
transform: function(transformer) {
return transformer.transformFinally(this);
},
visit: function(visitor) {
visitor.visitFinally(this);
},
get type() {
return FINALLY;
}
}, {}, ParseTree);
var FOR_IN_STATEMENT = ParseTreeType.FOR_IN_STATEMENT;
var ForInStatement = function ForInStatement(location, initializer, collection, body) {
this.location = location;
this.initializer = initializer;
this.collection = collection;
this.body = body;
};
($traceurRuntime.createClass)(ForInStatement, {
transform: function(transformer) {
return transformer.transformForInStatement(this);
},
visit: function(visitor) {
visitor.visitForInStatement(this);
},
get type() {
return FOR_IN_STATEMENT;
}
}, {}, ParseTree);
var FOR_OF_STATEMENT = ParseTreeType.FOR_OF_STATEMENT;
var ForOfStatement = function ForOfStatement(location, initializer, collection, body) {
this.location = location;
this.initializer = initializer;
this.collection = collection;
this.body = body;
};
($traceurRuntime.createClass)(ForOfStatement, {
transform: function(transformer) {
return transformer.transformForOfStatement(this);
},
visit: function(visitor) {
visitor.visitForOfStatement(this);
},
get type() {
return FOR_OF_STATEMENT;
}
}, {}, ParseTree);
var FOR_STATEMENT = ParseTreeType.FOR_STATEMENT;
var ForStatement = function ForStatement(location, initializer, condition, increment, body) {
this.location = location;
this.initializer = initializer;
this.condition = condition;
this.increment = increment;
this.body = body;
};
($traceurRuntime.createClass)(ForStatement, {
transform: function(transformer) {
return transformer.transformForStatement(this);
},
visit: function(visitor) {
visitor.visitForStatement(this);
},
get type() {
return FOR_STATEMENT;
}
}, {}, ParseTree);
var FORMAL_PARAMETER = ParseTreeType.FORMAL_PARAMETER;
var FormalParameter = function FormalParameter(location, parameter, typeAnnotation, annotations) {
this.location = location;
this.parameter = parameter;
this.typeAnnotation = typeAnnotation;
this.annotations = annotations;
};
($traceurRuntime.createClass)(FormalParameter, {
transform: function(transformer) {
return transformer.transformFormalParameter(this);
},
visit: function(visitor) {
visitor.visitFormalParameter(this);
},
get type() {
return FORMAL_PARAMETER;
}
}, {}, ParseTree);
var FORMAL_PARAMETER_LIST = ParseTreeType.FORMAL_PARAMETER_LIST;
var FormalParameterList = function FormalParameterList(location, parameters) {
this.location = location;
this.parameters = parameters;
};
($traceurRuntime.createClass)(FormalParameterList, {
transform: function(transformer) {
return transformer.transformFormalParameterList(this);
},
visit: function(visitor) {
visitor.visitFormalParameterList(this);
},
get type() {
return FORMAL_PARAMETER_LIST;
}
}, {}, ParseTree);
var FUNCTION_BODY = ParseTreeType.FUNCTION_BODY;
var FunctionBody = function FunctionBody(location, statements) {
this.location = location;
this.statements = statements;
};
($traceurRuntime.createClass)(FunctionBody, {
transform: function(transformer) {
return transformer.transformFunctionBody(this);
},
visit: function(visitor) {
visitor.visitFunctionBody(this);
},
get type() {
return FUNCTION_BODY;
}
}, {}, ParseTree);
var FUNCTION_DECLARATION = ParseTreeType.FUNCTION_DECLARATION;
var FunctionDeclaration = function FunctionDeclaration(location, name, functionKind, parameterList, typeAnnotation, annotations, body) {
this.location = location;
this.name = name;
this.functionKind = functionKind;
this.parameterList = parameterList;
this.typeAnnotation = typeAnnotation;
this.annotations = annotations;
this.body = body;
};
($traceurRuntime.createClass)(FunctionDeclaration, {
transform: function(transformer) {
return transformer.transformFunctionDeclaration(this);
},
visit: function(visitor) {
visitor.visitFunctionDeclaration(this);
},
get type() {
return FUNCTION_DECLARATION;
}
}, {}, ParseTree);
var FUNCTION_EXPRESSION = ParseTreeType.FUNCTION_EXPRESSION;
var FunctionExpression = function FunctionExpression(location, name, functionKind, parameterList, typeAnnotation, annotations, body) {
this.location = location;
this.name = name;
this.functionKind = functionKind;
this.parameterList = parameterList;
this.typeAnnotation = typeAnnotation;
this.annotations = annotations;
this.body = body;
};
($traceurRuntime.createClass)(FunctionExpression, {
transform: function(transformer) {
return transformer.transformFunctionExpression(this);
},
visit: function(visitor) {
visitor.visitFunctionExpression(this);
},
get type() {
return FUNCTION_EXPRESSION;
}
}, {}, ParseTree);
var GENERATOR_COMPREHENSION = ParseTreeType.GENERATOR_COMPREHENSION;
var GeneratorComprehension = function GeneratorComprehension(location, comprehensionList, expression) {
this.location = location;
this.comprehensionList = comprehensionList;
this.expression = expression;
};
($traceurRuntime.createClass)(GeneratorComprehension, {
transform: function(transformer) {
return transformer.transformGeneratorComprehension(this);
},
visit: function(visitor) {
visitor.visitGeneratorComprehension(this);
},
get type() {
return GENERATOR_COMPREHENSION;
}
}, {}, ParseTree);
var GET_ACCESSOR = ParseTreeType.GET_ACCESSOR;
var GetAccessor = function GetAccessor(location, isStatic, name, typeAnnotation, annotations, body) {
this.location = location;
this.isStatic = isStatic;
this.name = name;
this.typeAnnotation = typeAnnotation;
this.annotations = annotations;
this.body = body;
};
($traceurRuntime.createClass)(GetAccessor, {
transform: function(transformer) {
return transformer.transformGetAccessor(this);
},
visit: function(visitor) {
visitor.visitGetAccessor(this);
},
get type() {
return GET_ACCESSOR;
}
}, {}, ParseTree);
var IDENTIFIER_EXPRESSION = ParseTreeType.IDENTIFIER_EXPRESSION;
var IdentifierExpression = function IdentifierExpression(location, identifierToken) {
this.location = location;
this.identifierToken = identifierToken;
};
($traceurRuntime.createClass)(IdentifierExpression, {
transform: function(transformer) {
return transformer.transformIdentifierExpression(this);
},
visit: function(visitor) {
visitor.visitIdentifierExpression(this);
},
get type() {
return IDENTIFIER_EXPRESSION;
}
}, {}, ParseTree);
var IF_STATEMENT = ParseTreeType.IF_STATEMENT;
var IfStatement = function IfStatement(location, condition, ifClause, elseClause) {
this.location = location;
this.condition = condition;
this.ifClause = ifClause;
this.elseClause = elseClause;
};
($traceurRuntime.createClass)(IfStatement, {
transform: function(transformer) {
return transformer.transformIfStatement(this);
},
visit: function(visitor) {
visitor.visitIfStatement(this);
},
get type() {
return IF_STATEMENT;
}
}, {}, ParseTree);
var IMPORTED_BINDING = ParseTreeType.IMPORTED_BINDING;
var ImportedBinding = function ImportedBinding(location, binding) {
this.location = location;
this.binding = binding;
};
($traceurRuntime.createClass)(ImportedBinding, {
transform: function(transformer) {
return transformer.transformImportedBinding(this);
},
visit: function(visitor) {
visitor.visitImportedBinding(this);
},
get type() {
return IMPORTED_BINDING;
}
}, {}, ParseTree);
var IMPORT_DECLARATION = ParseTreeType.IMPORT_DECLARATION;
var ImportDeclaration = function ImportDeclaration(location, importClause, moduleSpecifier) {
this.location = location;
this.importClause = importClause;
this.moduleSpecifier = moduleSpecifier;
};
($traceurRuntime.createClass)(ImportDeclaration, {
transform: function(transformer) {
return transformer.transformImportDeclaration(this);
},
visit: function(visitor) {
visitor.visitImportDeclaration(this);
},
get type() {
return IMPORT_DECLARATION;
}
}, {}, ParseTree);
var IMPORT_SPECIFIER = ParseTreeType.IMPORT_SPECIFIER;
var ImportSpecifier = function ImportSpecifier(location, lhs, rhs) {
this.location = location;
this.lhs = lhs;
this.rhs = rhs;
};
($traceurRuntime.createClass)(ImportSpecifier, {
transform: function(transformer) {
return transformer.transformImportSpecifier(this);
},
visit: function(visitor) {
visitor.visitImportSpecifier(this);
},
get type() {
return IMPORT_SPECIFIER;
}
}, {}, ParseTree);
var IMPORT_SPECIFIER_SET = ParseTreeType.IMPORT_SPECIFIER_SET;
var ImportSpecifierSet = function ImportSpecifierSet(location, specifiers) {
this.location = location;
this.specifiers = specifiers;
};
($traceurRuntime.createClass)(ImportSpecifierSet, {
transform: function(transformer) {
return transformer.transformImportSpecifierSet(this);
},
visit: function(visitor) {
visitor.visitImportSpecifierSet(this);
},
get type() {
return IMPORT_SPECIFIER_SET;
}
}, {}, ParseTree);
var LABELLED_STATEMENT = ParseTreeType.LABELLED_STATEMENT;
var LabelledStatement = function LabelledStatement(location, name, statement) {
this.location = location;
this.name = name;
this.statement = statement;
};
($traceurRuntime.createClass)(LabelledStatement, {
transform: function(transformer) {
return transformer.transformLabelledStatement(this);
},
visit: function(visitor) {
visitor.visitLabelledStatement(this);
},
get type() {
return LABELLED_STATEMENT;
}
}, {}, ParseTree);
var LITERAL_EXPRESSION = ParseTreeType.LITERAL_EXPRESSION;
var LiteralExpression = function LiteralExpression(location, literalToken) {
this.location = location;
this.literalToken = literalToken;
};
($traceurRuntime.createClass)(LiteralExpression, {
transform: function(transformer) {
return transformer.transformLiteralExpression(this);
},
visit: function(visitor) {
visitor.visitLiteralExpression(this);
},
get type() {
return LITERAL_EXPRESSION;
}
}, {}, ParseTree);
var LITERAL_PROPERTY_NAME = ParseTreeType.LITERAL_PROPERTY_NAME;
var LiteralPropertyName = function LiteralPropertyName(location, literalToken) {
this.location = location;
this.literalToken = literalToken;
};
($traceurRuntime.createClass)(LiteralPropertyName, {
transform: function(transformer) {
return transformer.transformLiteralPropertyName(this);
},
visit: function(visitor) {
visitor.visitLiteralPropertyName(this);
},
get type() {
return LITERAL_PROPERTY_NAME;
}
}, {}, ParseTree);
var MEMBER_EXPRESSION = ParseTreeType.MEMBER_EXPRESSION;
var MemberExpression = function MemberExpression(location, operand, memberName) {
this.location = location;
this.operand = operand;
this.memberName = memberName;
};
($traceurRuntime.createClass)(MemberExpression, {
transform: function(transformer) {
return transformer.transformMemberExpression(this);
},
visit: function(visitor) {
visitor.visitMemberExpression(this);
},
get type() {
return MEMBER_EXPRESSION;
}
}, {}, ParseTree);
var MEMBER_LOOKUP_EXPRESSION = ParseTreeType.MEMBER_LOOKUP_EXPRESSION;
var MemberLookupExpression = function MemberLookupExpression(location, operand, memberExpression) {
this.location = location;
this.operand = operand;
this.memberExpression = memberExpression;
};
($traceurRuntime.createClass)(MemberLookupExpression, {
transform: function(transformer) {
return transformer.transformMemberLookupExpression(this);
},
visit: function(visitor) {
visitor.visitMemberLookupExpression(this);
},
get type() {
return MEMBER_LOOKUP_EXPRESSION;
}
}, {}, ParseTree);
var MODULE = ParseTreeType.MODULE;
var Module = function Module(location, scriptItemList, moduleName) {
this.location = location;
this.scriptItemList = scriptItemList;
this.moduleName = moduleName;
};
($traceurRuntime.createClass)(Module, {
transform: function(transformer) {
return transformer.transformModule(this);
},
visit: function(visitor) {
visitor.visitModule(this);
},
get type() {
return MODULE;
}
}, {}, ParseTree);
var MODULE_DECLARATION = ParseTreeType.MODULE_DECLARATION;
var ModuleDeclaration = function ModuleDeclaration(location, identifier, expression) {
this.location = location;
this.identifier = identifier;
this.expression = expression;
};
($traceurRuntime.createClass)(ModuleDeclaration, {
transform: function(transformer) {
return transformer.transformModuleDeclaration(this);
},
visit: function(visitor) {
visitor.visitModuleDeclaration(this);
},
get type() {
return MODULE_DECLARATION;
}
}, {}, ParseTree);
var MODULE_SPECIFIER = ParseTreeType.MODULE_SPECIFIER;
var ModuleSpecifier = function ModuleSpecifier(location, token) {
this.location = location;
this.token = token;
};
($traceurRuntime.createClass)(ModuleSpecifier, {
transform: function(transformer) {
return transformer.transformModuleSpecifier(this);
},
visit: function(visitor) {
visitor.visitModuleSpecifier(this);
},
get type() {
return MODULE_SPECIFIER;
}
}, {}, ParseTree);
var NAMED_EXPORT = ParseTreeType.NAMED_EXPORT;
var NamedExport = function NamedExport(location, moduleSpecifier, specifierSet) {
this.location = location;
this.moduleSpecifier = moduleSpecifier;
this.specifierSet = specifierSet;
};
($traceurRuntime.createClass)(NamedExport, {
transform: function(transformer) {
return transformer.transformNamedExport(this);
},
visit: function(visitor) {
visitor.visitNamedExport(this);
},
get type() {
return NAMED_EXPORT;
}
}, {}, ParseTree);
var NEW_EXPRESSION = ParseTreeType.NEW_EXPRESSION;
var NewExpression = function NewExpression(location, operand, args) {
this.location = location;
this.operand = operand;
this.args = args;
};
($traceurRuntime.createClass)(NewExpression, {
transform: function(transformer) {
return transformer.transformNewExpression(this);
},
visit: function(visitor) {
visitor.visitNewExpression(this);
},
get type() {
return NEW_EXPRESSION;
}
}, {}, ParseTree);
var OBJECT_LITERAL_EXPRESSION = ParseTreeType.OBJECT_LITERAL_EXPRESSION;
var ObjectLiteralExpression = function ObjectLiteralExpression(location, propertyNameAndValues) {
this.location = location;
this.propertyNameAndValues = propertyNameAndValues;
};
($traceurRuntime.createClass)(ObjectLiteralExpression, {
transform: function(transformer) {
return transformer.transformObjectLiteralExpression(this);
},
visit: function(visitor) {
visitor.visitObjectLiteralExpression(this);
},
get type() {
return OBJECT_LITERAL_EXPRESSION;
}
}, {}, ParseTree);
var OBJECT_PATTERN = ParseTreeType.OBJECT_PATTERN;
var ObjectPattern = function ObjectPattern(location, fields) {
this.location = location;
this.fields = fields;
};
($traceurRuntime.createClass)(ObjectPattern, {
transform: function(transformer) {
return transformer.transformObjectPattern(this);
},
visit: function(visitor) {
visitor.visitObjectPattern(this);
},
get type() {
return OBJECT_PATTERN;
}
}, {}, ParseTree);
var OBJECT_PATTERN_FIELD = ParseTreeType.OBJECT_PATTERN_FIELD;
var ObjectPatternField = function ObjectPatternField(location, name, element) {
this.location = location;
this.name = name;
this.element = element;
};
($traceurRuntime.createClass)(ObjectPatternField, {
transform: function(transformer) {
return transformer.transformObjectPatternField(this);
},
visit: function(visitor) {
visitor.visitObjectPatternField(this);
},
get type() {
return OBJECT_PATTERN_FIELD;
}
}, {}, ParseTree);
var PAREN_EXPRESSION = ParseTreeType.PAREN_EXPRESSION;
var ParenExpression = function ParenExpression(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(ParenExpression, {
transform: function(transformer) {
return transformer.transformParenExpression(this);
},
visit: function(visitor) {
visitor.visitParenExpression(this);
},
get type() {
return PAREN_EXPRESSION;
}
}, {}, ParseTree);
var POSTFIX_EXPRESSION = ParseTreeType.POSTFIX_EXPRESSION;
var PostfixExpression = function PostfixExpression(location, operand, operator) {
this.location = location;
this.operand = operand;
this.operator = operator;
};
($traceurRuntime.createClass)(PostfixExpression, {
transform: function(transformer) {
return transformer.transformPostfixExpression(this);
},
visit: function(visitor) {
visitor.visitPostfixExpression(this);
},
get type() {
return POSTFIX_EXPRESSION;
}
}, {}, ParseTree);
var PREDEFINED_TYPE = ParseTreeType.PREDEFINED_TYPE;
var PredefinedType = function PredefinedType(location, typeToken) {
this.location = location;
this.typeToken = typeToken;
};
($traceurRuntime.createClass)(PredefinedType, {
transform: function(transformer) {
return transformer.transformPredefinedType(this);
},
visit: function(visitor) {
visitor.visitPredefinedType(this);
},
get type() {
return PREDEFINED_TYPE;
}
}, {}, ParseTree);
var SCRIPT = ParseTreeType.SCRIPT;
var Script = function Script(location, scriptItemList, moduleName) {
this.location = location;
this.scriptItemList = scriptItemList;
this.moduleName = moduleName;
};
($traceurRuntime.createClass)(Script, {
transform: function(transformer) {
return transformer.transformScript(this);
},
visit: function(visitor) {
visitor.visitScript(this);
},
get type() {
return SCRIPT;
}
}, {}, ParseTree);
var PROPERTY_METHOD_ASSIGNMENT = ParseTreeType.PROPERTY_METHOD_ASSIGNMENT;
var PropertyMethodAssignment = function PropertyMethodAssignment(location, isStatic, functionKind, name, parameterList, typeAnnotation, annotations, body) {
this.location = location;
this.isStatic = isStatic;
this.functionKind = functionKind;
this.name = name;
this.parameterList = parameterList;
this.typeAnnotation = typeAnnotation;
this.annotations = annotations;
this.body = body;
};
($traceurRuntime.createClass)(PropertyMethodAssignment, {
transform: function(transformer) {
return transformer.transformPropertyMethodAssignment(this);
},
visit: function(visitor) {
visitor.visitPropertyMethodAssignment(this);
},
get type() {
return PROPERTY_METHOD_ASSIGNMENT;
}
}, {}, ParseTree);
var PROPERTY_NAME_ASSIGNMENT = ParseTreeType.PROPERTY_NAME_ASSIGNMENT;
var PropertyNameAssignment = function PropertyNameAssignment(location, name, value) {
this.location = location;
this.name = name;
this.value = value;
};
($traceurRuntime.createClass)(PropertyNameAssignment, {
transform: function(transformer) {
return transformer.transformPropertyNameAssignment(this);
},
visit: function(visitor) {
visitor.visitPropertyNameAssignment(this);
},
get type() {
return PROPERTY_NAME_ASSIGNMENT;
}
}, {}, ParseTree);
var PROPERTY_NAME_SHORTHAND = ParseTreeType.PROPERTY_NAME_SHORTHAND;
var PropertyNameShorthand = function PropertyNameShorthand(location, name) {
this.location = location;
this.name = name;
};
($traceurRuntime.createClass)(PropertyNameShorthand, {
transform: function(transformer) {
return transformer.transformPropertyNameShorthand(this);
},
visit: function(visitor) {
visitor.visitPropertyNameShorthand(this);
},
get type() {
return PROPERTY_NAME_SHORTHAND;
}
}, {}, ParseTree);
var REST_PARAMETER = ParseTreeType.REST_PARAMETER;
var RestParameter = function RestParameter(location, identifier) {
this.location = location;
this.identifier = identifier;
};
($traceurRuntime.createClass)(RestParameter, {
transform: function(transformer) {
return transformer.transformRestParameter(this);
},
visit: function(visitor) {
visitor.visitRestParameter(this);
},
get type() {
return REST_PARAMETER;
}
}, {}, ParseTree);
var RETURN_STATEMENT = ParseTreeType.RETURN_STATEMENT;
var ReturnStatement = function ReturnStatement(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(ReturnStatement, {
transform: function(transformer) {
return transformer.transformReturnStatement(this);
},
visit: function(visitor) {
visitor.visitReturnStatement(this);
},
get type() {
return RETURN_STATEMENT;
}
}, {}, ParseTree);
var SET_ACCESSOR = ParseTreeType.SET_ACCESSOR;
var SetAccessor = function SetAccessor(location, isStatic, name, parameterList, annotations, body) {
this.location = location;
this.isStatic = isStatic;
this.name = name;
this.parameterList = parameterList;
this.annotations = annotations;
this.body = body;
};
($traceurRuntime.createClass)(SetAccessor, {
transform: function(transformer) {
return transformer.transformSetAccessor(this);
},
visit: function(visitor) {
visitor.visitSetAccessor(this);
},
get type() {
return SET_ACCESSOR;
}
}, {}, ParseTree);
var SPREAD_EXPRESSION = ParseTreeType.SPREAD_EXPRESSION;
var SpreadExpression = function SpreadExpression(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(SpreadExpression, {
transform: function(transformer) {
return transformer.transformSpreadExpression(this);
},
visit: function(visitor) {
visitor.visitSpreadExpression(this);
},
get type() {
return SPREAD_EXPRESSION;
}
}, {}, ParseTree);
var SPREAD_PATTERN_ELEMENT = ParseTreeType.SPREAD_PATTERN_ELEMENT;
var SpreadPatternElement = function SpreadPatternElement(location, lvalue) {
this.location = location;
this.lvalue = lvalue;
};
($traceurRuntime.createClass)(SpreadPatternElement, {
transform: function(transformer) {
return transformer.transformSpreadPatternElement(this);
},
visit: function(visitor) {
visitor.visitSpreadPatternElement(this);
},
get type() {
return SPREAD_PATTERN_ELEMENT;
}
}, {}, ParseTree);
var SUPER_EXPRESSION = ParseTreeType.SUPER_EXPRESSION;
var SuperExpression = function SuperExpression(location) {
this.location = location;
};
($traceurRuntime.createClass)(SuperExpression, {
transform: function(transformer) {
return transformer.transformSuperExpression(this);
},
visit: function(visitor) {
visitor.visitSuperExpression(this);
},
get type() {
return SUPER_EXPRESSION;
}
}, {}, ParseTree);
var SWITCH_STATEMENT = ParseTreeType.SWITCH_STATEMENT;
var SwitchStatement = function SwitchStatement(location, expression, caseClauses) {
this.location = location;
this.expression = expression;
this.caseClauses = caseClauses;
};
($traceurRuntime.createClass)(SwitchStatement, {
transform: function(transformer) {
return transformer.transformSwitchStatement(this);
},
visit: function(visitor) {
visitor.visitSwitchStatement(this);
},
get type() {
return SWITCH_STATEMENT;
}
}, {}, ParseTree);
var SYNTAX_ERROR_TREE = ParseTreeType.SYNTAX_ERROR_TREE;
var SyntaxErrorTree = function SyntaxErrorTree(location, nextToken, message) {
this.location = location;
this.nextToken = nextToken;
this.message = message;
};
($traceurRuntime.createClass)(SyntaxErrorTree, {
transform: function(transformer) {
return transformer.transformSyntaxErrorTree(this);
},
visit: function(visitor) {
visitor.visitSyntaxErrorTree(this);
},
get type() {
return SYNTAX_ERROR_TREE;
}
}, {}, ParseTree);
var TEMPLATE_LITERAL_EXPRESSION = ParseTreeType.TEMPLATE_LITERAL_EXPRESSION;
var TemplateLiteralExpression = function TemplateLiteralExpression(location, operand, elements) {
this.location = location;
this.operand = operand;
this.elements = elements;
};
($traceurRuntime.createClass)(TemplateLiteralExpression, {
transform: function(transformer) {
return transformer.transformTemplateLiteralExpression(this);
},
visit: function(visitor) {
visitor.visitTemplateLiteralExpression(this);
},
get type() {
return TEMPLATE_LITERAL_EXPRESSION;
}
}, {}, ParseTree);
var TEMPLATE_LITERAL_PORTION = ParseTreeType.TEMPLATE_LITERAL_PORTION;
var TemplateLiteralPortion = function TemplateLiteralPortion(location, value) {
this.location = location;
this.value = value;
};
($traceurRuntime.createClass)(TemplateLiteralPortion, {
transform: function(transformer) {
return transformer.transformTemplateLiteralPortion(this);
},
visit: function(visitor) {
visitor.visitTemplateLiteralPortion(this);
},
get type() {
return TEMPLATE_LITERAL_PORTION;
}
}, {}, ParseTree);
var TEMPLATE_SUBSTITUTION = ParseTreeType.TEMPLATE_SUBSTITUTION;
var TemplateSubstitution = function TemplateSubstitution(location, expression) {
this.location = location;
this.expression = expression;
};
($traceurRuntime.createClass)(TemplateSubstitution, {
transform: function(transformer) {
return transformer.transformTemplateSubstitution(this);
},
visit: function(visitor) {
visitor.visitTemplateSubstitution(this);
},
get type() {
return TEMPLATE_SUBSTITUTION;
}
}, {}, ParseTree);
var THIS_EXPRESSION = ParseTreeType.THIS_EXPRESSION;
var ThisExpression = function ThisExpression(location) {
this.location = location;
};
($traceurRuntime.createClass)(ThisExpression, {
transform: function(transformer) {
return transformer.transformThisExpression(this);
},
visit: function(visitor) {
visitor.visitThisExpression(this);
},
get type() {
return THIS_EXPRESSION;
}
}, {}, ParseTree);
var THROW_STATEMENT = ParseTreeType.THROW_STATEMENT;
var ThrowStatement = function ThrowStatement(location, value) {
this.location = location;
this.value = value;
};
($traceurRuntime.createClass)(ThrowStatement, {
transform: function(transformer) {
return transformer.transformThrowStatement(this);
},
visit: function(visitor) {
visitor.visitThrowStatement(this);
},
get type() {
return THROW_STATEMENT;
}
}, {}, ParseTree);
var TRY_STATEMENT = ParseTreeType.TRY_STATEMENT;
var TryStatement = function TryStatement(location, body, catchBlock, finallyBlock) {
this.location = location;
this.body = body;
this.catchBlock = catchBlock;
this.finallyBlock = finallyBlock;
};
($traceurRuntime.createClass)(TryStatement, {
transform: function(transformer) {
return transformer.transformTryStatement(this);
},
visit: function(visitor) {
visitor.visitTryStatement(this);
},
get type() {
return TRY_STATEMENT;
}
}, {}, ParseTree);
var TYPE_NAME = ParseTreeType.TYPE_NAME;
var TypeName = function TypeName(location, moduleName, name) {
this.location = location;
this.moduleName = moduleName;
this.name = name;
};
($traceurRuntime.createClass)(TypeName, {
transform: function(transformer) {
return transformer.transformTypeName(this);
},
visit: function(visitor) {
visitor.visitTypeName(this);
},
get type() {
return TYPE_NAME;
}
}, {}, ParseTree);
var UNARY_EXPRESSION = ParseTreeType.UNARY_EXPRESSION;
var UnaryExpression = function UnaryExpression(location, operator, operand) {
this.location = location;
this.operator = operator;
this.operand = operand;
};
($traceurRuntime.createClass)(UnaryExpression, {
transform: function(transformer) {
return transformer.transformUnaryExpression(this);
},
visit: function(visitor) {
visitor.visitUnaryExpression(this);
},
get type() {
return UNARY_EXPRESSION;
}
}, {}, ParseTree);
var VARIABLE_DECLARATION = ParseTreeType.VARIABLE_DECLARATION;
var VariableDeclaration = function VariableDeclaration(location, lvalue, typeAnnotation, initializer) {
this.location = location;
this.lvalue = lvalue;
this.typeAnnotation = typeAnnotation;
this.initializer = initializer;
};
($traceurRuntime.createClass)(VariableDeclaration, {
transform: function(transformer) {
return transformer.transformVariableDeclaration(this);
},
visit: function(visitor) {
visitor.visitVariableDeclaration(this);
},
get type() {
return VARIABLE_DECLARATION;
}
}, {}, ParseTree);
var VARIABLE_DECLARATION_LIST = ParseTreeType.VARIABLE_DECLARATION_LIST;
var VariableDeclarationList = function VariableDeclarationList(location, declarationType, declarations) {
this.location = location;
this.declarationType = declarationType;
this.declarations = declarations;
};
($traceurRuntime.createClass)(VariableDeclarationList, {
transform: function(transformer) {
return transformer.transformVariableDeclarationList(this);
},
visit: function(visitor) {
visitor.visitVariableDeclarationList(this);
},
get type() {
return VARIABLE_DECLARATION_LIST;
}
}, {}, ParseTree);
var VARIABLE_STATEMENT = ParseTreeType.VARIABLE_STATEMENT;
var VariableStatement = function VariableStatement(location, declarations) {
this.location = location;
this.declarations = declarations;
};
($traceurRuntime.createClass)(VariableStatement, {
transform: function(transformer) {
return transformer.transformVariableStatement(this);
},
visit: function(visitor) {
visitor.visitVariableStatement(this);
},
get type() {
return VARIABLE_STATEMENT;
}
}, {}, ParseTree);
var WHILE_STATEMENT = ParseTreeType.WHILE_STATEMENT;
var WhileStatement = function WhileStatement(location, condition, body) {
this.location = location;
this.condition = condition;
this.body = body;
};
($traceurRuntime.createClass)(WhileStatement, {
transform: function(transformer) {
return transformer.transformWhileStatement(this);
},
visit: function(visitor) {
visitor.visitWhileStatement(this);
},
get type() {
return WHILE_STATEMENT;
}
}, {}, ParseTree);
var WITH_STATEMENT = ParseTreeType.WITH_STATEMENT;
var WithStatement = function WithStatement(location, expression, body) {
this.location = location;
this.expression = expression;
this.body = body;
};
($traceurRuntime.createClass)(WithStatement, {
transform: function(transformer) {
return transformer.transformWithStatement(this);
},
visit: function(visitor) {
visitor.visitWithStatement(this);
},
get type() {
return WITH_STATEMENT;
}
}, {}, ParseTree);
var YIELD_EXPRESSION = ParseTreeType.YIELD_EXPRESSION;
var YieldExpression = function YieldExpression(location, expression, isYieldFor) {
this.location = location;
this.expression = expression;
this.isYieldFor = isYieldFor;
};
($traceurRuntime.createClass)(YieldExpression, {
transform: function(transformer) {
return transformer.transformYieldExpression(this);
},
visit: function(visitor) {
visitor.visitYieldExpression(this);
},
get type() {
return YIELD_EXPRESSION;
}
}, {}, ParseTree);
return {
get Annotation() {
return Annotation;
},
get AnonBlock() {
return AnonBlock;
},
get ArgumentList() {
return ArgumentList;
},
get ArrayComprehension() {
return ArrayComprehension;
},
get ArrayLiteralExpression() {
return ArrayLiteralExpression;
},
get ArrayPattern() {
return ArrayPattern;
},
get ArrowFunctionExpression() {
return ArrowFunctionExpression;
},
get AssignmentElement() {
return AssignmentElement;
},
get AwaitExpression() {
return AwaitExpression;
},
get BinaryExpression() {
return BinaryExpression;
},
get BindingElement() {
return BindingElement;
},
get BindingIdentifier() {
return BindingIdentifier;
},
get Block() {
return Block;
},
get BreakStatement() {
return BreakStatement;
},
get CallExpression() {
return CallExpression;
},
get CaseClause() {
return CaseClause;
},
get Catch() {
return Catch;
},
get ClassDeclaration() {
return ClassDeclaration;
},
get ClassExpression() {
return ClassExpression;
},
get CommaExpression() {
return CommaExpression;
},
get ComprehensionFor() {
return ComprehensionFor;
},
get ComprehensionIf() {
return ComprehensionIf;
},
get ComputedPropertyName() {
return ComputedPropertyName;
},
get ConditionalExpression() {
return ConditionalExpression;
},
get ContinueStatement() {
return ContinueStatement;
},
get CoverFormals() {
return CoverFormals;
},
get CoverInitializedName() {
return CoverInitializedName;
},
get DebuggerStatement() {
return DebuggerStatement;
},
get DefaultClause() {
return DefaultClause;
},
get DoWhileStatement() {
return DoWhileStatement;
},
get EmptyStatement() {
return EmptyStatement;
},
get ExportDeclaration() {
return ExportDeclaration;
},
get ExportDefault() {
return ExportDefault;
},
get ExportSpecifier() {
return ExportSpecifier;
},
get ExportSpecifierSet() {
return ExportSpecifierSet;
},
get ExportStar() {
return ExportStar;
},
get ExpressionStatement() {
return ExpressionStatement;
},
get Finally() {
return Finally;
},
get ForInStatement() {
return ForInStatement;
},
get ForOfStatement() {
return ForOfStatement;
},
get ForStatement() {
return ForStatement;
},
get FormalParameter() {
return FormalParameter;
},
get FormalParameterList() {
return FormalParameterList;
},
get FunctionBody() {
return FunctionBody;
},
get FunctionDeclaration() {
return FunctionDeclaration;
},
get FunctionExpression() {
return FunctionExpression;
},
get GeneratorComprehension() {
return GeneratorComprehension;
},
get GetAccessor() {
return GetAccessor;
},
get IdentifierExpression() {
return IdentifierExpression;
},
get IfStatement() {
return IfStatement;
},
get ImportedBinding() {
return ImportedBinding;
},
get ImportDeclaration() {
return ImportDeclaration;
},
get ImportSpecifier() {
return ImportSpecifier;
},
get ImportSpecifierSet() {
return ImportSpecifierSet;
},
get LabelledStatement() {
return LabelledStatement;
},
get LiteralExpression() {
return LiteralExpression;
},
get LiteralPropertyName() {
return LiteralPropertyName;
},
get MemberExpression() {
return MemberExpression;
},
get MemberLookupExpression() {
return MemberLookupExpression;
},
get Module() {
return Module;
},
get ModuleDeclaration() {
return ModuleDeclaration;
},
get ModuleSpecifier() {
return ModuleSpecifier;
},
get NamedExport() {
return NamedExport;
},
get NewExpression() {
return NewExpression;
},
get ObjectLiteralExpression() {
return ObjectLiteralExpression;
},
get ObjectPattern() {
return ObjectPattern;
},
get ObjectPatternField() {
return ObjectPatternField;
},
get ParenExpression() {
return ParenExpression;
},
get PostfixExpression() {
return PostfixExpression;
},
get PredefinedType() {
return PredefinedType;
},
get Script() {
return Script;
},
get PropertyMethodAssignment() {
return PropertyMethodAssignment;
},
get PropertyNameAssignment() {
return PropertyNameAssignment;
},
get PropertyNameShorthand() {
return PropertyNameShorthand;
},
get RestParameter() {
return RestParameter;
},
get ReturnStatement() {
return ReturnStatement;
},
get SetAccessor() {
return SetAccessor;
},
get SpreadExpression() {
return SpreadExpression;
},
get SpreadPatternElement() {
return SpreadPatternElement;
},
get SuperExpression() {
return SuperExpression;
},
get SwitchStatement() {
return SwitchStatement;
},
get SyntaxErrorTree() {
return SyntaxErrorTree;
},
get TemplateLiteralExpression() {
return TemplateLiteralExpression;
},
get TemplateLiteralPortion() {
return TemplateLiteralPortion;
},
get TemplateSubstitution() {
return TemplateSubstitution;
},
get ThisExpression() {
return ThisExpression;
},
get ThrowStatement() {
return ThrowStatement;
},
get TryStatement() {
return TryStatement;
},
get TypeName() {
return TypeName;
},
get UnaryExpression() {
return UnaryExpression;
},
get VariableDeclaration() {
return VariableDeclaration;
},
get VariableDeclarationList() {
return VariableDeclarationList;
},
get VariableStatement() {
return VariableStatement;
},
get WhileStatement() {
return WhileStatement;
},
get WithStatement() {
return WithStatement;
},
get YieldExpression() {
return YieldExpression;
}
};
});
System.register("traceur@0.0.52/src/semantics/getVariableName", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/getVariableName";
var $__57 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
BindingIdentifier = $__57.BindingIdentifier,
IdentifierExpression = $__57.IdentifierExpression;
var IdentifierToken = System.get("traceur@0.0.52/src/syntax/IdentifierToken").IdentifierToken;
function getVariableName(name) {
if (name instanceof IdentifierExpression) {
name = name.identifierToken;
} else if (name instanceof BindingIdentifier) {
name = name.identifierToken;
}
if (name instanceof IdentifierToken) {
name = name.value;
}
return name;
}
return {get getVariableName() {
return getVariableName;
}};
});
System.register("traceur@0.0.52/src/semantics/util", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/util";
var $__59 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
IDENTIFIER_EXPRESSION = $__59.IDENTIFIER_EXPRESSION,
LITERAL_EXPRESSION = $__59.LITERAL_EXPRESSION,
PAREN_EXPRESSION = $__59.PAREN_EXPRESSION,
UNARY_EXPRESSION = $__59.UNARY_EXPRESSION;
var UNDEFINED = System.get("traceur@0.0.52/src/syntax/PredefinedName").UNDEFINED;
var VOID = System.get("traceur@0.0.52/src/syntax/TokenType").VOID;
function hasUseStrict(list) {
for (var i = 0; i < list.length; i++) {
if (!list[i].isDirectivePrologue())
return false;
if (list[i].isUseStrictDirective())
return true;
}
return false;
}
function isUndefined(tree) {
if (tree.type === PAREN_EXPRESSION)
return isUndefined(tree.expression);
return tree.type === IDENTIFIER_EXPRESSION && tree.identifierToken.value === UNDEFINED;
}
function isVoidExpression(tree) {
if (tree.type === PAREN_EXPRESSION)
return isVoidExpression(tree.expression);
return tree.type === UNARY_EXPRESSION && tree.operator.type === VOID && isLiteralExpression(tree.operand);
}
function isLiteralExpression(tree) {
if (tree.type === PAREN_EXPRESSION)
return isLiteralExpression(tree.expression);
return tree.type === LITERAL_EXPRESSION;
}
return {
get hasUseStrict() {
return hasUseStrict;
},
get isUndefined() {
return isUndefined;
},
get isVoidExpression() {
return isVoidExpression;
},
get isLiteralExpression() {
return isLiteralExpression;
}
};
});
System.register("traceur@0.0.52/src/semantics/isTreeStrict", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/isTreeStrict";
var $__62 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
ARROW_FUNCTION_EXPRESSION = $__62.ARROW_FUNCTION_EXPRESSION,
CLASS_DECLARATION = $__62.CLASS_DECLARATION,
CLASS_EXPRESSION = $__62.CLASS_EXPRESSION,
FUNCTION_BODY = $__62.FUNCTION_BODY,
FUNCTION_DECLARATION = $__62.FUNCTION_DECLARATION,
FUNCTION_EXPRESSION = $__62.FUNCTION_EXPRESSION,
GET_ACCESSOR = $__62.GET_ACCESSOR,
MODULE = $__62.MODULE,
PROPERTY_METHOD_ASSIGNMENT = $__62.PROPERTY_METHOD_ASSIGNMENT,
SCRIPT = $__62.SCRIPT,
SET_ACCESSOR = $__62.SET_ACCESSOR;
var hasUseStrict = System.get("traceur@0.0.52/src/semantics/util").hasUseStrict;
function isTreeStrict(tree) {
switch (tree.type) {
case CLASS_DECLARATION:
case CLASS_EXPRESSION:
case MODULE:
return true;
case FUNCTION_BODY:
return hasUseStrict(tree.statements);
case FUNCTION_EXPRESSION:
case FUNCTION_DECLARATION:
case PROPERTY_METHOD_ASSIGNMENT:
return isTreeStrict(tree.body);
case ARROW_FUNCTION_EXPRESSION:
if (tree.body.type === FUNCTION_BODY) {
return isTreeStrict(tree.body);
}
return false;
case GET_ACCESSOR:
case SET_ACCESSOR:
return isTreeStrict(tree.body);
case SCRIPT:
return hasUseStrict(tree.scriptItemList);
default:
return false;
}
}
return {get isTreeStrict() {
return isTreeStrict;
}};
});
System.register("traceur@0.0.52/src/semantics/Scope", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/Scope";
var $__64 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BLOCK = $__64.BLOCK,
CATCH = $__64.CATCH;
var VAR = System.get("traceur@0.0.52/src/syntax/TokenType").VAR;
var getVariableName = System.get("traceur@0.0.52/src/semantics/getVariableName").getVariableName;
var isTreeStrict = System.get("traceur@0.0.52/src/semantics/isTreeStrict").isTreeStrict;
function reportDuplicateVar(reporter, tree, name) {
reporter.reportError(tree.location && tree.location.start, ("Duplicate declaration, " + name));
}
var Scope = function Scope(parent, tree) {
this.parent = parent;
this.tree = tree;
this.variableDeclarations = Object.create(null);
this.lexicalDeclarations = Object.create(null);
this.strictMode = parent && parent.strictMode || isTreeStrict(tree);
};
($traceurRuntime.createClass)(Scope, {
addBinding: function(tree, type, reporter) {
if (type === VAR) {
this.addVar(tree, reporter);
} else {
this.addDeclaration(tree, type, reporter);
}
},
addVar: function(tree, reporter) {
var name = getVariableName(tree);
if (this.lexicalDeclarations[name]) {
reportDuplicateVar(reporter, tree, name);
return;
}
this.variableDeclarations[name] = {
type: VAR,
tree: tree
};
if (!this.isVarScope && this.parent) {
this.parent.addVar(tree, reporter);
}
},
addDeclaration: function(tree, type, reporter) {
var name = getVariableName(tree);
if (this.lexicalDeclarations[name] || this.variableDeclarations[name]) {
reportDuplicateVar(reporter, tree, name);
return;
}
this.lexicalDeclarations[name] = {
type: type,
tree: tree
};
},
get isVarScope() {
switch (this.tree.type) {
case BLOCK:
case CATCH:
return false;
}
return true;
},
getVarScope: function() {
if (this.isVarScope) {
return this;
}
if (this.parent) {
return this.parent.getVarScope();
}
return null;
},
getBinding: function(tree) {
var name = getVariableName(tree);
return this.getBinding_(name);
},
getBinding_: function(name) {
var b = this.lexicalDeclarations[name];
if (b) {
return b;
}
b = this.variableDeclarations[name];
if (b && this.isVarScope) {
return b;
}
if (this.parent) {
return this.parent.getBinding_(name);
}
return null;
},
getVariableBindingNames: function() {
var names = Object.create(null);
for (var name in this.variableDeclarations) {
names[name] = true;
}
return names;
},
getLexicalBindingNames: function() {
var names = Object.create(null);
for (var name in this.lexicalDeclarations) {
names[name] = true;
}
return names;
}
}, {});
return {get Scope() {
return Scope;
}};
});
System.register("traceur@0.0.52/src/semantics/ScopeVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/ScopeVisitor";
var Map = System.get("traceur@0.0.52/src/runtime/polyfills/Map").Map;
var ParseTreeVisitor = System.get("traceur@0.0.52/src/syntax/ParseTreeVisitor").ParseTreeVisitor;
var VAR = System.get("traceur@0.0.52/src/syntax/TokenType").VAR;
var Scope = System.get("traceur@0.0.52/src/semantics/Scope").Scope;
var $__73 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
COMPREHENSION_FOR = $__73.COMPREHENSION_FOR,
VARIABLE_DECLARATION_LIST = $__73.VARIABLE_DECLARATION_LIST;
var ScopeVisitor = function ScopeVisitor() {
this.map_ = new Map();
this.scope = null;
this.withBlockCounter_ = 0;
};
var $ScopeVisitor = ScopeVisitor;
($traceurRuntime.createClass)(ScopeVisitor, {
getScopeForTree: function(tree) {
return this.map_.get(tree);
},
pushScope: function(tree) {
var scope = new Scope(this.scope, tree);
this.map_.set(tree, scope);
return this.scope = scope;
},
popScope: function(scope) {
if (this.scope !== scope) {
throw new Error('ScopeVisitor scope mismatch');
}
this.scope = scope.parent;
},
visitScript: function(tree) {
var scope = this.pushScope(tree);
$traceurRuntime.superCall(this, $ScopeVisitor.prototype, "visitScript", [tree]);
this.popScope(scope);
},
visitModule: function(tree) {
var scope = this.pushScope(tree);
$traceurRuntime.superCall(this, $ScopeVisitor.prototype, "visitModule", [tree]);
this.popScope(scope);
},
visitBlock: function(tree) {
var scope = this.pushScope(tree);
$traceurRuntime.superCall(this, $ScopeVisitor.prototype, "visitBlock", [tree]);
this.popScope(scope);
},
visitCatch: function(tree) {
var scope = this.pushScope(tree);
this.visitAny(tree.binding);
this.visitList(tree.catchBody.statements);
this.popScope(scope);
},
visitFunctionBodyForScope: function(tree) {
var parameterList = arguments[1] !== (void 0) ? arguments[1] : tree.parameterList;
var scope = this.pushScope(tree);
this.visitAny(parameterList);
this.visitAny(tree.body);
this.popScope(scope);
},
visitFunctionExpression: function(tree) {
this.visitFunctionBodyForScope(tree);
},
visitFunctionDeclaration: function(tree) {
this.visitAny(tree.name);
this.visitFunctionBodyForScope(tree);
},
visitArrowFunctionExpression: function(tree) {
this.visitFunctionBodyForScope(tree);
},
visitGetAccessor: function(tree) {
this.visitFunctionBodyForScope(tree, null);
},
visitSetAccessor: function(tree) {
this.visitFunctionBodyForScope(tree);
},
visitPropertyMethodAssignment: function(tree) {
this.visitFunctionBodyForScope(tree);
},
visitClassDeclaration: function(tree) {
this.visitAny(tree.superClass);
var scope = this.pushScope(tree);
this.visitAny(tree.name);
this.visitList(tree.elements);
this.popScope(scope);
},
visitClassExpression: function(tree) {
this.visitAny(tree.superClass);
var scope;
if (tree.name) {
scope = this.pushScope(tree);
this.visitAny(tree.name);
}
this.visitList(tree.elements);
if (tree.name) {
this.popScope(scope);
}
},
visitWithStatement: function(tree) {
this.visitAny(tree.expression);
this.withBlockCounter_++;
this.visitAny(tree.body);
this.withBlockCounter_--;
},
get inWithBlock() {
return this.withBlockCounter_ > 0;
},
visitLoop_: function(tree, func) {
if (tree.initializer.type !== VARIABLE_DECLARATION_LIST || tree.initializer.declarationType === VAR) {
func();
return;
}
var scope = this.pushScope(tree);
func();
this.popScope(scope);
},
visitForInStatement: function(tree) {
var $__74 = this;
this.visitLoop_(tree, (function() {
return $traceurRuntime.superCall($__74, $ScopeVisitor.prototype, "visitForInStatement", [tree]);
}));
},
visitForOfStatement: function(tree) {
var $__74 = this;
this.visitLoop_(tree, (function() {
return $traceurRuntime.superCall($__74, $ScopeVisitor.prototype, "visitForOfStatement", [tree]);
}));
},
visitForStatement: function(tree) {
var $__74 = this;
if (!tree.initializer) {
$traceurRuntime.superCall(this, $ScopeVisitor.prototype, "visitForStatement", [tree]);
} else {
this.visitLoop_(tree, (function() {
return $traceurRuntime.superCall($__74, $ScopeVisitor.prototype, "visitForStatement", [tree]);
}));
}
},
visitComprehension_: function(tree) {
var scopes = [];
for (var i = 0; i < tree.comprehensionList.length; i++) {
var scope = null;
if (tree.comprehensionList[i].type === COMPREHENSION_FOR) {
scope = this.pushScope(tree.comprehensionList[i]);
}
scopes.push(scope);
this.visitAny(tree.comprehensionList[i]);
}
this.visitAny(tree.expression);
for (var i = scopes.length - 1; i >= 0; i--) {
if (scopes[i]) {
this.popScope(scopes[i]);
}
}
},
visitArrayComprehension: function(tree) {
this.visitComprehension_(tree);
},
visitGeneratorComprehension: function(tree) {
this.visitComprehension_(tree);
}
}, {}, ParseTreeVisitor);
return {get ScopeVisitor() {
return ScopeVisitor;
}};
});
System.register("traceur@0.0.52/src/semantics/ScopeChainBuilder", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/ScopeChainBuilder";
var $__75 = System.get("traceur@0.0.52/src/syntax/TokenType"),
CONST = $__75.CONST,
LET = $__75.LET,
VAR = $__75.VAR;
var ScopeVisitor = System.get("traceur@0.0.52/src/semantics/ScopeVisitor").ScopeVisitor;
var ScopeChainBuilder = function ScopeChainBuilder(reporter) {
$traceurRuntime.superCall(this, $ScopeChainBuilder.prototype, "constructor", []);
this.reporter_ = reporter;
this.declarationType_ = null;
};
var $ScopeChainBuilder = ScopeChainBuilder;
($traceurRuntime.createClass)(ScopeChainBuilder, {
visitCatch: function(tree) {
var scope = this.pushScope(tree);
this.declarationType_ = LET;
this.visitAny(tree.binding);
this.visitList(tree.catchBody.statements);
this.popScope(scope);
},
visitImportedBinding: function(tree) {
this.declarationType_ = CONST;
$traceurRuntime.superCall(this, $ScopeChainBuilder.prototype, "visitImportedBinding", [tree]);
},
visitImportSpecifier: function(tree) {
this.declarationType_ = CONST;
if (tree.rhs) {
this.declareVariable(tree.rhs);
} else {
this.declareVariable(tree.lhs);
}
},
visitModuleDeclaration: function(tree) {
this.declarationType_ = CONST;
this.declareVariable(tree.identifier);
},
visitVariableDeclarationList: function(tree) {
this.declarationType_ = tree.declarationType;
$traceurRuntime.superCall(this, $ScopeChainBuilder.prototype, "visitVariableDeclarationList", [tree]);
},
visitBindingIdentifier: function(tree) {
this.declareVariable(tree);
},
visitFunctionExpression: function(tree) {
var scope = this.pushScope(tree);
if (tree.name) {
this.declarationType_ = CONST;
this.visitAny(tree.name);
}
this.visitAny(tree.parameterList);
this.visitAny(tree.body);
this.popScope(scope);
},
visitFormalParameter: function(tree) {
this.declarationType_ = VAR;
$traceurRuntime.superCall(this, $ScopeChainBuilder.prototype, "visitFormalParameter", [tree]);
},
visitFunctionDeclaration: function(tree) {
if (this.scope) {
if (this.scope.isVarScope) {
this.declarationType_ = VAR;
this.visitAny(tree.name);
} else {
if (!this.scope.strictMode) {
var varScope = this.scope.getVarScope();
if (varScope) {
varScope.addVar(tree.name, this.reporter_);
}
}
this.declarationType_ = LET;
this.visitAny(tree.name);
}
}
this.visitFunctionBodyForScope(tree, tree.parameterList, tree.body);
},
visitClassDeclaration: function(tree) {
this.visitAny(tree.superClass);
this.declarationType_ = LET;
this.visitAny(tree.name);
var scope = this.pushScope(tree);
this.declarationType_ = CONST;
this.visitAny(tree.name);
this.visitList(tree.elements);
this.popScope(scope);
},
visitClassExpression: function(tree) {
this.visitAny(tree.superClass);
var scope;
if (tree.name) {
scope = this.pushScope(tree);
this.declarationType_ = CONST;
this.visitAny(tree.name);
}
this.visitList(tree.elements);
if (tree.name) {
this.popScope(scope);
}
},
visitComprehensionFor: function(tree) {
this.declarationType_ = LET;
$traceurRuntime.superCall(this, $ScopeChainBuilder.prototype, "visitComprehensionFor", [tree]);
},
declareVariable: function(tree) {
this.scope.addBinding(tree, this.declarationType_, this.reporter_);
}
}, {}, ScopeVisitor);
return {get ScopeChainBuilder() {
return ScopeChainBuilder;
}};
});
System.register("traceur@0.0.52/src/semantics/ConstChecker", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/ConstChecker";
var IDENTIFIER_EXPRESSION = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType").IDENTIFIER_EXPRESSION;
var $__79 = System.get("traceur@0.0.52/src/syntax/TokenType"),
CONST = $__79.CONST,
MINUS_MINUS = $__79.MINUS_MINUS,
PLUS_PLUS = $__79.PLUS_PLUS;
var ScopeVisitor = System.get("traceur@0.0.52/src/semantics/ScopeVisitor").ScopeVisitor;
var ScopeChainBuilder = System.get("traceur@0.0.52/src/semantics/ScopeChainBuilder").ScopeChainBuilder;
var getVariableName = System.get("traceur@0.0.52/src/semantics/getVariableName").getVariableName;
var ConstChecker = function ConstChecker(scopeBuilder, reporter) {
$traceurRuntime.superCall(this, $ConstChecker.prototype, "constructor", []);
this.scopeBuilder_ = scopeBuilder;
this.reporter_ = reporter;
};
var $ConstChecker = ConstChecker;
($traceurRuntime.createClass)(ConstChecker, {
pushScope: function(tree) {
return this.scope = this.scopeBuilder_.getScopeForTree(tree);
},
visitUnaryExpression: function(tree) {
if (tree.operand.type === IDENTIFIER_EXPRESSION && (tree.operator.type === PLUS_PLUS || tree.operator.type === MINUS_MINUS)) {
this.validateMutation_(tree.operand);
}
$traceurRuntime.superCall(this, $ConstChecker.prototype, "visitUnaryExpression", [tree]);
},
visitPostfixExpression: function(tree) {
if (tree.operand.type === IDENTIFIER_EXPRESSION) {
this.validateMutation_(tree.operand);
}
$traceurRuntime.superCall(this, $ConstChecker.prototype, "visitPostfixExpression", [tree]);
},
visitBinaryExpression: function(tree) {
if (tree.left.type === IDENTIFIER_EXPRESSION && tree.operator.isAssignmentOperator()) {
this.validateMutation_(tree.left);
}
$traceurRuntime.superCall(this, $ConstChecker.prototype, "visitBinaryExpression", [tree]);
},
validateMutation_: function(identifierExpression) {
if (this.inWithBlock) {
return;
}
var binding = this.scope.getBinding(identifierExpression);
if (binding === null) {
return;
}
var $__84 = $traceurRuntime.assertObject(binding),
type = $__84.type,
tree = $__84.tree;
if (type === CONST) {
this.reportError_(identifierExpression.location, (getVariableName(tree) + " is read-only"));
}
},
reportError_: function(location, message) {
this.reporter_.reportError(location.start, message);
}
}, {}, ScopeVisitor);
function validate(tree, reporter) {
var builder = new ScopeChainBuilder(reporter);
builder.visitAny(tree);
var checker = new ConstChecker(builder, reporter);
checker.visitAny(tree);
}
return {
get ConstChecker() {
return ConstChecker;
},
get validate() {
return validate;
}
};
});
System.register("traceur@0.0.52/src/semantics/FreeVariableChecker", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/FreeVariableChecker";
var $__85 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
FUNCTION_DECLARATION = $__85.FUNCTION_DECLARATION,
FUNCTION_EXPRESSION = $__85.FUNCTION_EXPRESSION,
GET_ACCESSOR = $__85.GET_ACCESSOR,
IDENTIFIER_EXPRESSION = $__85.IDENTIFIER_EXPRESSION,
MODULE = $__85.MODULE,
PROPERTY_METHOD_ASSIGNMENT = $__85.PROPERTY_METHOD_ASSIGNMENT,
SET_ACCESSOR = $__85.SET_ACCESSOR;
var TYPEOF = System.get("traceur@0.0.52/src/syntax/TokenType").TYPEOF;
var ScopeVisitor = System.get("traceur@0.0.52/src/semantics/ScopeVisitor").ScopeVisitor;
var ScopeChainBuilder = System.get("traceur@0.0.52/src/semantics/ScopeChainBuilder").ScopeChainBuilder;
var getVariableName = System.get("traceur@0.0.52/src/semantics/getVariableName").getVariableName;
function hasArgumentsInScope(scope) {
for (; scope; scope = scope.parent) {
switch (scope.tree.type) {
case FUNCTION_DECLARATION:
case FUNCTION_EXPRESSION:
case GET_ACCESSOR:
case PROPERTY_METHOD_ASSIGNMENT:
case SET_ACCESSOR:
return true;
}
}
return false;
}
function inModuleScope(scope) {
for (; scope; scope = scope.parent) {
if (scope.tree.type === MODULE) {
return true;
}
}
return false;
}
var FreeVariableChecker = function FreeVariableChecker(scopeBuilder, reporter) {
var global = arguments[2] !== (void 0) ? arguments[2] : Object.create(null);
$traceurRuntime.superCall(this, $FreeVariableChecker.prototype, "constructor", []);
this.scopeBuilder_ = scopeBuilder;
this.reporter_ = reporter;
this.global_ = global;
};
var $FreeVariableChecker = FreeVariableChecker;
($traceurRuntime.createClass)(FreeVariableChecker, {
pushScope: function(tree) {
return this.scope = this.scopeBuilder_.getScopeForTree(tree);
},
visitUnaryExpression: function(tree) {
if (tree.operator.type === TYPEOF && tree.operand.type === IDENTIFIER_EXPRESSION) {
var scope = this.scope;
var binding = scope.getBinding(tree.operand);
if (!binding) {
scope.addVar(tree.operand, this.reporter_);
}
} else {
$traceurRuntime.superCall(this, $FreeVariableChecker.prototype, "visitUnaryExpression", [tree]);
}
},
visitIdentifierExpression: function(tree) {
if (this.inWithBlock) {
return;
}
var scope = this.scope;
var binding = scope.getBinding(tree);
if (binding) {
return;
}
var name = getVariableName(tree);
if (name === 'arguments' && hasArgumentsInScope(scope)) {
return;
}
if (name === '__moduleName' && inModuleScope(scope)) {
return;
}
if (!(name in this.global_)) {
this.reporter_.reportError(tree.location.start, (name + " is not defined"));
}
}
}, {}, ScopeVisitor);
function validate(tree, reporter) {
var global = arguments[2] !== (void 0) ? arguments[2] : Reflect.global;
var builder = new ScopeChainBuilder(reporter);
builder.visitAny(tree);
var checker = new FreeVariableChecker(builder, reporter, global);
checker.visitAny(tree);
}
return {get validate() {
return validate;
}};
});
System.register("traceur@0.0.52/src/util/assert", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/assert";
var options = System.get("traceur@0.0.52/src/Options").options;
function assert(b) {
if (!b && options.debug)
throw Error('Assertion failed');
}
return {get assert() {
return assert;
}};
});
System.register("traceur@0.0.52/src/syntax/LiteralToken", [], function() {
"use strict";
var $__95;
var __moduleName = "traceur@0.0.52/src/syntax/LiteralToken";
var Token = System.get("traceur@0.0.52/src/syntax/Token").Token;
var $__93 = System.get("traceur@0.0.52/src/syntax/TokenType"),
NULL = $__93.NULL,
NUMBER = $__93.NUMBER,
STRING = $__93.STRING;
var StringParser = function StringParser(value) {
this.value = value;
this.index = 0;
};
($traceurRuntime.createClass)(StringParser, ($__95 = {}, Object.defineProperty($__95, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__95, "next", {
value: function() {
if (++this.index >= this.value.length - 1)
return {
value: undefined,
done: true
};
return {
value: this.value[this.index],
done: false
};
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__95, "parse", {
value: function() {
if (this.value.indexOf('\\') === -1)
return this.value.slice(1, -1);
var result = '';
for (var $__96 = this[Symbol.iterator](),
$__97; !($__97 = $__96.next()).done; ) {
var ch = $__97.value;
{
result += ch === '\\' ? this.parseEscapeSequence() : ch;
}
}
return result;
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__95, "parseEscapeSequence", {
value: function() {
var ch = this.next().value;
switch (ch) {
case '\n':
case '\r':
case '\u2028':
case '\u2029':
return '';
case '0':
return '\0';
case 'b':
return '\b';
case 'f':
return '\f';
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'v':
return '\v';
case 'x':
return String.fromCharCode(parseInt(this.next().value + this.next().value, 16));
case 'u':
return String.fromCharCode(parseInt(this.next().value + this.next().value + this.next().value + this.next().value, 16));
default:
if (Number(ch) < 8)
throw new Error('Octal literals are not supported');
return ch;
}
},
configurable: true,
enumerable: true,
writable: true
}), $__95), {});
var LiteralToken = function LiteralToken(type, value, location) {
this.type = type;
this.location = location;
this.value = value;
};
($traceurRuntime.createClass)(LiteralToken, {
toString: function() {
return this.value;
},
get processedValue() {
switch (this.type) {
case NULL:
return null;
case NUMBER:
var value = this.value;
if (value.charCodeAt(0) === 48) {
switch (value.charCodeAt(1)) {
case 66:
case 98:
return parseInt(this.value.slice(2), 2);
case 79:
case 111:
return parseInt(this.value.slice(2), 8);
}
}
return Number(this.value);
case STRING:
var parser = new StringParser(this.value);
return parser.parse();
default:
throw new Error('Not implemented');
}
}
}, {}, Token);
return {get LiteralToken() {
return LiteralToken;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ParseTreeFactory", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ParseTreeFactory";
var IdentifierToken = System.get("traceur@0.0.52/src/syntax/IdentifierToken").IdentifierToken;
var LiteralToken = System.get("traceur@0.0.52/src/syntax/LiteralToken").LiteralToken;
var $__100 = System.get("traceur@0.0.52/src/syntax/trees/ParseTree"),
ParseTree = $__100.ParseTree,
ParseTreeType = $__100.ParseTreeType;
var $__101 = System.get("traceur@0.0.52/src/syntax/PredefinedName"),
CALL = $__101.CALL,
CREATE = $__101.CREATE,
DEFINE_PROPERTY = $__101.DEFINE_PROPERTY,
FREEZE = $__101.FREEZE,
OBJECT = $__101.OBJECT,
UNDEFINED = $__101.UNDEFINED;
var Token = System.get("traceur@0.0.52/src/syntax/Token").Token;
var $__103 = System.get("traceur@0.0.52/src/syntax/TokenType"),
EQUAL = $__103.EQUAL,
FALSE = $__103.FALSE,
NULL = $__103.NULL,
NUMBER = $__103.NUMBER,
STRING = $__103.STRING,
TRUE = $__103.TRUE,
VOID = $__103.VOID;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var $__105 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
ArgumentList = $__105.ArgumentList,
ArrayLiteralExpression = $__105.ArrayLiteralExpression,
BinaryExpression = $__105.BinaryExpression,
BindingIdentifier = $__105.BindingIdentifier,
Block = $__105.Block,
BreakStatement = $__105.BreakStatement,
CallExpression = $__105.CallExpression,
CaseClause = $__105.CaseClause,
Catch = $__105.Catch,
ClassDeclaration = $__105.ClassDeclaration,
CommaExpression = $__105.CommaExpression,
ConditionalExpression = $__105.ConditionalExpression,
ContinueStatement = $__105.ContinueStatement,
DefaultClause = $__105.DefaultClause,
DoWhileStatement = $__105.DoWhileStatement,
EmptyStatement = $__105.EmptyStatement,
ExpressionStatement = $__105.ExpressionStatement,
Finally = $__105.Finally,
ForInStatement = $__105.ForInStatement,
ForOfStatement = $__105.ForOfStatement,
ForStatement = $__105.ForStatement,
FormalParameterList = $__105.FormalParameterList,
FunctionBody = $__105.FunctionBody,
FunctionExpression = $__105.FunctionExpression,
IdentifierExpression = $__105.IdentifierExpression,
IfStatement = $__105.IfStatement,
LiteralExpression = $__105.LiteralExpression,
LiteralPropertyName = $__105.LiteralPropertyName,
MemberExpression = $__105.MemberExpression,
MemberLookupExpression = $__105.MemberLookupExpression,
NewExpression = $__105.NewExpression,
ObjectLiteralExpression = $__105.ObjectLiteralExpression,
ParenExpression = $__105.ParenExpression,
PostfixExpression = $__105.PostfixExpression,
Script = $__105.Script,
PropertyNameAssignment = $__105.PropertyNameAssignment,
RestParameter = $__105.RestParameter,
ReturnStatement = $__105.ReturnStatement,
SpreadExpression = $__105.SpreadExpression,
SwitchStatement = $__105.SwitchStatement,
ThisExpression = $__105.ThisExpression,
ThrowStatement = $__105.ThrowStatement,
TryStatement = $__105.TryStatement,
UnaryExpression = $__105.UnaryExpression,
VariableDeclaration = $__105.VariableDeclaration,
VariableDeclarationList = $__105.VariableDeclarationList,
VariableStatement = $__105.VariableStatement,
WhileStatement = $__105.WhileStatement,
WithStatement = $__105.WithStatement,
YieldExpression = $__105.YieldExpression;
var slice = Array.prototype.slice.call.bind(Array.prototype.slice);
var map = Array.prototype.map.call.bind(Array.prototype.map);
function createOperatorToken(operator) {
return new Token(operator, null);
}
function createIdentifierToken(identifier) {
return new IdentifierToken(null, identifier);
}
function createStringLiteralToken(value) {
return new LiteralToken(STRING, JSON.stringify(value), null);
}
function createBooleanLiteralToken(value) {
return new Token(value ? TRUE : FALSE, null);
}
function createNullLiteralToken() {
return new LiteralToken(NULL, 'null', null);
}
function createNumberLiteralToken(value) {
return new LiteralToken(NUMBER, String(value), null);
}
function createEmptyParameterList() {
return new FormalParameterList(null, []);
}
function createArgumentList(list) {
return new ArgumentList(null, list);
}
function createEmptyArgumentList() {
return createArgumentList([]);
}
function createArrayLiteralExpression(list) {
return new ArrayLiteralExpression(null, list);
}
function createEmptyArrayLiteralExpression() {
return createArrayLiteralExpression([]);
}
function createAssignmentExpression(lhs, rhs) {
return new BinaryExpression(null, lhs, createOperatorToken(EQUAL), rhs);
}
function createBinaryExpression(left, operator, right) {
return new BinaryExpression(null, left, operator, right);
}
function createBindingIdentifier(identifier) {
if (typeof identifier === 'string')
identifier = createIdentifierToken(identifier);
else if (identifier.type === ParseTreeType.BINDING_IDENTIFIER)
return identifier;
else if (identifier.type === ParseTreeType.IDENTIFIER_EXPRESSION)
return new BindingIdentifier(identifier.location, identifier.identifierToken);
return new BindingIdentifier(null, identifier);
}
function createEmptyStatement() {
return new EmptyStatement(null);
}
function createEmptyBlock() {
return createBlock([]);
}
function createBlock(statements) {
return new Block(null, statements);
}
function createFunctionBody(statements) {
return new FunctionBody(null, statements);
}
function createScopedExpression(body, scope) {
assert(body.type === 'FUNCTION_BODY');
return createCallCall(createParenExpression(createFunctionExpression(createEmptyParameterList(), body)), scope);
}
function createImmediatelyInvokedFunctionExpression(body) {
assert(body.type === 'FUNCTION_BODY');
return createCallExpression(createParenExpression(createFunctionExpression(createEmptyParameterList(), body)));
}
function createCallExpression(operand) {
var args = arguments[1] !== (void 0) ? arguments[1] : createEmptyArgumentList();
return new CallExpression(null, operand, args);
}
function createBreakStatement() {
var name = arguments[0] !== (void 0) ? arguments[0] : null;
return new BreakStatement(null, name);
}
function createCallCall(func, thisExpression) {
return createCallExpression(createMemberExpression(func, CALL), createArgumentList([thisExpression]));
}
function createCaseClause(expression, statements) {
return new CaseClause(null, expression, statements);
}
function createCatch(identifier, catchBody) {
identifier = createBindingIdentifier(identifier);
return new Catch(null, identifier, catchBody);
}
function createClassDeclaration(name, superClass, elements) {
return new ClassDeclaration(null, name, superClass, elements, []);
}
function createCommaExpression(expressions) {
return new CommaExpression(null, expressions);
}
function createConditionalExpression(condition, left, right) {
return new ConditionalExpression(null, condition, left, right);
}
function createContinueStatement() {
var name = arguments[0] !== (void 0) ? arguments[0] : null;
return new ContinueStatement(null, name);
}
function createDefaultClause(statements) {
return new DefaultClause(null, statements);
}
function createDoWhileStatement(body, condition) {
return new DoWhileStatement(null, body, condition);
}
function createAssignmentStatement(lhs, rhs) {
return createExpressionStatement(createAssignmentExpression(lhs, rhs));
}
function createCallStatement(operand) {
var args = arguments[1];
return createExpressionStatement(createCallExpression(operand, args));
}
function createExpressionStatement(expression) {
return new ExpressionStatement(null, expression);
}
function createFinally(block) {
return new Finally(null, block);
}
function createForOfStatement(initializer, collection, body) {
return new ForOfStatement(null, initializer, collection, body);
}
function createForInStatement(initializer, collection, body) {
return new ForInStatement(null, initializer, collection, body);
}
function createForStatement(variables, condition, increment, body) {
return new ForStatement(null, variables, condition, increment, body);
}
function createFunctionExpression(parameterList, body) {
assert(body.type === 'FUNCTION_BODY');
return new FunctionExpression(null, null, false, parameterList, null, [], body);
}
function createIdentifierExpression(identifier) {
if (typeof identifier == 'string')
identifier = createIdentifierToken(identifier);
else if (identifier instanceof BindingIdentifier)
identifier = identifier.identifierToken;
return new IdentifierExpression(null, identifier);
}
function createUndefinedExpression() {
return createIdentifierExpression(UNDEFINED);
}
function createIfStatement(condition, ifClause) {
var elseClause = arguments[2] !== (void 0) ? arguments[2] : null;
return new IfStatement(null, condition, ifClause, elseClause);
}
function createStringLiteral(value) {
return new LiteralExpression(null, createStringLiteralToken(value));
}
function createBooleanLiteral(value) {
return new LiteralExpression(null, createBooleanLiteralToken(value));
}
function createTrueLiteral() {
return createBooleanLiteral(true);
}
function createFalseLiteral() {
return createBooleanLiteral(false);
}
function createNullLiteral() {
return new LiteralExpression(null, createNullLiteralToken());
}
function createNumberLiteral(value) {
return new LiteralExpression(null, createNumberLiteralToken(value));
}
function createMemberExpression(operand, memberName, memberNames) {
if (typeof operand == 'string' || operand instanceof IdentifierToken)
operand = createIdentifierExpression(operand);
if (typeof memberName == 'string')
memberName = createIdentifierToken(memberName);
if (memberName instanceof LiteralToken)
memberName = new LiteralExpression(null, memberName);
var tree = memberName instanceof LiteralExpression ? new MemberLookupExpression(null, operand, memberName) : new MemberExpression(null, operand, memberName);
for (var i = 2; i < arguments.length; i++) {
tree = createMemberExpression(tree, arguments[i]);
}
return tree;
}
function createMemberLookupExpression(operand, memberExpression) {
return new MemberLookupExpression(null, operand, memberExpression);
}
function createThisExpression() {
return new ThisExpression(null);
}
function createNewExpression(operand, args) {
return new NewExpression(null, operand, args);
}
function createObjectFreeze(value) {
return createCallExpression(createMemberExpression(OBJECT, FREEZE), createArgumentList([value]));
}
function createObjectCreate(protoExpression, descriptors) {
var argumentList = [protoExpression];
if (descriptors)
argumentList.push(descriptors);
return createCallExpression(createMemberExpression(OBJECT, CREATE), createArgumentList(argumentList));
}
function createPropertyDescriptor(descr) {
var propertyNameAndValues = Object.keys(descr).map(function(name) {
var value = descr[name];
if (!(value instanceof ParseTree))
value = createBooleanLiteral(!!value);
return createPropertyNameAssignment(name, value);
});
return createObjectLiteralExpression(propertyNameAndValues);
}
function createDefineProperty(tree, name, descr) {
if (typeof name === 'string')
name = createStringLiteral(name);
return createCallExpression(createMemberExpression(OBJECT, DEFINE_PROPERTY), createArgumentList([tree, name, createPropertyDescriptor(descr)]));
}
function createObjectLiteralExpression(propertyNameAndValues) {
return new ObjectLiteralExpression(null, propertyNameAndValues);
}
function createParenExpression(expression) {
return new ParenExpression(null, expression);
}
function createPostfixExpression(operand, operator) {
return new PostfixExpression(null, operand, operator);
}
function createScript(scriptItemList) {
return new Script(null, scriptItemList);
}
function createPropertyNameAssignment(identifier, value) {
if (typeof identifier == 'string')
identifier = createLiteralPropertyName(identifier);
return new PropertyNameAssignment(null, identifier, value);
}
function createLiteralPropertyName(name) {
return new LiteralPropertyName(null, createIdentifierToken(name));
}
function createRestParameter(identifier) {
return new RestParameter(null, createBindingIdentifier(identifier));
}
function createReturnStatement(expression) {
return new ReturnStatement(null, expression);
}
function createYieldStatement(expression, isYieldFor) {
return createExpressionStatement(new YieldExpression(null, expression, isYieldFor));
}
function createSpreadExpression(expression) {
return new SpreadExpression(null, expression);
}
function createSwitchStatement(expression, caseClauses) {
return new SwitchStatement(null, expression, caseClauses);
}
function createThrowStatement(value) {
return new ThrowStatement(null, value);
}
function createTryStatement(body, catchBlock) {
var finallyBlock = arguments[2] !== (void 0) ? arguments[2] : null;
return new TryStatement(null, body, catchBlock, finallyBlock);
}
function createUnaryExpression(operator, operand) {
return new UnaryExpression(null, operator, operand);
}
function createUseStrictDirective() {
return createExpressionStatement(createStringLiteral('use strict'));
}
function createVariableDeclarationList(binding, identifierOrDeclarations, initializer) {
if (identifierOrDeclarations instanceof Array) {
var declarations = identifierOrDeclarations;
return new VariableDeclarationList(null, binding, declarations);
}
var identifier = identifierOrDeclarations;
return createVariableDeclarationList(binding, [createVariableDeclaration(identifier, initializer)]);
}
function createVariableDeclaration(identifier, initializer) {
if (!(identifier instanceof ParseTree) || identifier.type !== ParseTreeType.BINDING_IDENTIFIER && identifier.type !== ParseTreeType.OBJECT_PATTERN && identifier.type !== ParseTreeType.ARRAY_PATTERN) {
identifier = createBindingIdentifier(identifier);
}
return new VariableDeclaration(null, identifier, null, initializer);
}
function createVariableStatement(listOrBinding, identifier, initializer) {
if (listOrBinding instanceof VariableDeclarationList)
return new VariableStatement(null, listOrBinding);
var binding = listOrBinding;
var list = createVariableDeclarationList(binding, identifier, initializer);
return createVariableStatement(list);
}
function createVoid0() {
return createParenExpression(createUnaryExpression(createOperatorToken(VOID), createNumberLiteral(0)));
}
function createWhileStatement(condition, body) {
return new WhileStatement(null, condition, body);
}
function createWithStatement(expression, body) {
return new WithStatement(null, expression, body);
}
function createAssignStateStatement(state) {
return createAssignmentStatement(createMemberExpression('$ctx', 'state'), createNumberLiteral(state));
}
return {
get createOperatorToken() {
return createOperatorToken;
},
get createIdentifierToken() {
return createIdentifierToken;
},
get createStringLiteralToken() {
return createStringLiteralToken;
},
get createBooleanLiteralToken() {
return createBooleanLiteralToken;
},
get createNullLiteralToken() {
return createNullLiteralToken;
},
get createNumberLiteralToken() {
return createNumberLiteralToken;
},
get createEmptyParameterList() {
return createEmptyParameterList;
},
get createArgumentList() {
return createArgumentList;
},
get createEmptyArgumentList() {
return createEmptyArgumentList;
},
get createArrayLiteralExpression() {
return createArrayLiteralExpression;
},
get createEmptyArrayLiteralExpression() {
return createEmptyArrayLiteralExpression;
},
get createAssignmentExpression() {
return createAssignmentExpression;
},
get createBinaryExpression() {
return createBinaryExpression;
},
get createBindingIdentifier() {
return createBindingIdentifier;
},
get createEmptyStatement() {
return createEmptyStatement;
},
get createEmptyBlock() {
return createEmptyBlock;
},
get createBlock() {
return createBlock;
},
get createFunctionBody() {
return createFunctionBody;
},
get createScopedExpression() {
return createScopedExpression;
},
get createImmediatelyInvokedFunctionExpression() {
return createImmediatelyInvokedFunctionExpression;
},
get createCallExpression() {
return createCallExpression;
},
get createBreakStatement() {
return createBreakStatement;
},
get createCaseClause() {
return createCaseClause;
},
get createCatch() {
return createCatch;
},
get createClassDeclaration() {
return createClassDeclaration;
},
get createCommaExpression() {
return createCommaExpression;
},
get createConditionalExpression() {
return createConditionalExpression;
},
get createContinueStatement() {
return createContinueStatement;
},
get createDefaultClause() {
return createDefaultClause;
},
get createDoWhileStatement() {
return createDoWhileStatement;
},
get createAssignmentStatement() {
return createAssignmentStatement;
},
get createCallStatement() {
return createCallStatement;
},
get createExpressionStatement() {
return createExpressionStatement;
},
get createFinally() {
return createFinally;
},
get createForOfStatement() {
return createForOfStatement;
},
get createForInStatement() {
return createForInStatement;
},
get createForStatement() {
return createForStatement;
},
get createFunctionExpression() {
return createFunctionExpression;
},
get createIdentifierExpression() {
return createIdentifierExpression;
},
get createUndefinedExpression() {
return createUndefinedExpression;
},
get createIfStatement() {
return createIfStatement;
},
get createStringLiteral() {
return createStringLiteral;
},
get createBooleanLiteral() {
return createBooleanLiteral;
},
get createTrueLiteral() {
return createTrueLiteral;
},
get createFalseLiteral() {
return createFalseLiteral;
},
get createNullLiteral() {
return createNullLiteral;
},
get createNumberLiteral() {
return createNumberLiteral;
},
get createMemberExpression() {
return createMemberExpression;
},
get createMemberLookupExpression() {
return createMemberLookupExpression;
},
get createThisExpression() {
return createThisExpression;
},
get createNewExpression() {
return createNewExpression;
},
get createObjectFreeze() {
return createObjectFreeze;
},
get createObjectCreate() {
return createObjectCreate;
},
get createPropertyDescriptor() {
return createPropertyDescriptor;
},
get createDefineProperty() {
return createDefineProperty;
},
get createObjectLiteralExpression() {
return createObjectLiteralExpression;
},
get createParenExpression() {
return createParenExpression;
},
get createPostfixExpression() {
return createPostfixExpression;
},
get createScript() {
return createScript;
},
get createPropertyNameAssignment() {
return createPropertyNameAssignment;
},
get createReturnStatement() {
return createReturnStatement;
},
get createYieldStatement() {
return createYieldStatement;
},
get createSwitchStatement() {
return createSwitchStatement;
},
get createThrowStatement() {
return createThrowStatement;
},
get createTryStatement() {
return createTryStatement;
},
get createUnaryExpression() {
return createUnaryExpression;
},
get createUseStrictDirective() {
return createUseStrictDirective;
},
get createVariableDeclarationList() {
return createVariableDeclarationList;
},
get createVariableDeclaration() {
return createVariableDeclaration;
},
get createVariableStatement() {
return createVariableStatement;
},
get createVoid0() {
return createVoid0;
},
get createWhileStatement() {
return createWhileStatement;
},
get createWithStatement() {
return createWithStatement;
},
get createAssignStateStatement() {
return createAssignStateStatement;
}
};
});
System.register("traceur@0.0.52/src/codegeneration/FindVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/FindVisitor";
var ParseTreeVisitor = System.get("traceur@0.0.52/src/syntax/ParseTreeVisitor").ParseTreeVisitor;
var FindVisitor = function FindVisitor(tree) {
var keepOnGoing = arguments[1];
this.found_ = false;
this.shouldContinue_ = true;
this.keepOnGoing_ = keepOnGoing;
this.visitAny(tree);
};
($traceurRuntime.createClass)(FindVisitor, {
get found() {
return this.found_;
},
set found(v) {
if (v) {
this.found_ = true;
if (!this.keepOnGoing_)
this.shouldContinue_ = false;
}
},
visitAny: function(tree) {
this.shouldContinue_ && tree && tree.visit(this);
},
visitList: function(list) {
if (list) {
for (var i = 0; this.shouldContinue_ && i < list.length; i++) {
this.visitAny(list[i]);
}
}
}
}, {}, ParseTreeVisitor);
return {get FindVisitor() {
return FindVisitor;
}};
});
System.register("traceur@0.0.52/src/syntax/Keywords", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/Keywords";
var keywords = ['break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'export', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'let', 'new', 'return', 'super', 'switch', 'this', 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with', 'enum', 'extends', 'null', 'true', 'false'];
var strictKeywords = ['implements', 'interface', 'package', 'private', 'protected', 'public', 'static', 'yield'];
var keywordsByName = Object.create(null);
var NORMAL_KEYWORD = 1;
var STRICT_KEYWORD = 2;
keywords.forEach((function(value) {
keywordsByName[value] = NORMAL_KEYWORD;
}));
strictKeywords.forEach((function(value) {
keywordsByName[value] = STRICT_KEYWORD;
}));
function getKeywordType(value) {
return keywordsByName[value];
}
function isStrictKeyword(value) {
return getKeywordType(value) === STRICT_KEYWORD;
}
return {
get NORMAL_KEYWORD() {
return NORMAL_KEYWORD;
},
get STRICT_KEYWORD() {
return STRICT_KEYWORD;
},
get getKeywordType() {
return getKeywordType;
},
get isStrictKeyword() {
return isStrictKeyword;
}
};
});
System.register("traceur@0.0.52/src/staticsemantics/StrictParams", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/staticsemantics/StrictParams";
var ParseTreeVisitor = System.get("traceur@0.0.52/src/syntax/ParseTreeVisitor").ParseTreeVisitor;
var isStrictKeyword = System.get("traceur@0.0.52/src/syntax/Keywords").isStrictKeyword;
var StrictParams = function StrictParams(errorReporter) {
$traceurRuntime.superCall(this, $StrictParams.prototype, "constructor", []);
this.errorReporter = errorReporter;
};
var $StrictParams = StrictParams;
($traceurRuntime.createClass)(StrictParams, {visitBindingIdentifier: function(tree) {
var name = tree.identifierToken.toString();
if (isStrictKeyword(name)) {
this.errorReporter.reportError(tree.location.start, (name + " is a reserved identifier"));
}
}}, {visit: function(tree, errorReporter) {
new $StrictParams(errorReporter).visitAny(tree);
}}, ParseTreeVisitor);
return {get StrictParams() {
return StrictParams;
}};
});
System.register("traceur@0.0.52/src/util/SourceRange", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/SourceRange";
var SourceRange = function SourceRange(start, end) {
this.start = start;
this.end = end;
};
($traceurRuntime.createClass)(SourceRange, {toString: function() {
var str = this.start.source.contents;
return str.slice(this.start.offset, this.end.offset);
}}, {});
return {get SourceRange() {
return SourceRange;
}};
});
System.register("traceur@0.0.52/src/util/ErrorReporter", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/ErrorReporter";
var ErrorReporter = function ErrorReporter() {
this.hadError_ = false;
};
($traceurRuntime.createClass)(ErrorReporter, {
reportError: function(location, message) {
this.hadError_ = true;
this.reportMessageInternal(location, message);
},
reportMessageInternal: function(location, message) {
if (location)
message = (location + ": " + message);
console.error(message);
},
hadError: function() {
return this.hadError_;
},
clearError: function() {
this.hadError_ = false;
}
}, {});
function format(location, text) {
var args = arguments[2];
var i = 0;
text = text.replace(/%./g, function(s) {
switch (s) {
case '%s':
return args && args[i++];
case '%%':
return '%';
}
return s;
});
if (location)
text = (location + ": " + text);
return text;
}
;
ErrorReporter.format = format;
return {
get ErrorReporter() {
return ErrorReporter;
},
get format() {
return format;
}
};
});
System.register("traceur@0.0.52/src/util/SyntaxErrorReporter", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/SyntaxErrorReporter";
var $__113 = System.get("traceur@0.0.52/src/util/ErrorReporter"),
ErrorReporter = $__113.ErrorReporter,
format = $__113.format;
var SyntaxErrorReporter = function SyntaxErrorReporter() {
$traceurRuntime.defaultSuperCall(this, $SyntaxErrorReporter.prototype, arguments);
};
var $SyntaxErrorReporter = SyntaxErrorReporter;
($traceurRuntime.createClass)(SyntaxErrorReporter, {reportMessageInternal: function(location, message) {
var s = format(location, message);
throw new SyntaxError(s);
}}, {}, ErrorReporter);
return {get SyntaxErrorReporter() {
return SyntaxErrorReporter;
}};
});
System.register("traceur@0.0.52/src/syntax/KeywordToken", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/KeywordToken";
var STRICT_KEYWORD = System.get("traceur@0.0.52/src/syntax/Keywords").STRICT_KEYWORD;
var Token = System.get("traceur@0.0.52/src/syntax/Token").Token;
var KeywordToken = function KeywordToken(type, keywordType, location) {
this.type = type;
this.location = location;
this.isStrictKeyword_ = keywordType === STRICT_KEYWORD;
};
($traceurRuntime.createClass)(KeywordToken, {
isKeyword: function() {
return true;
},
isStrictKeyword: function() {
return this.isStrictKeyword_;
}
}, {}, Token);
return {get KeywordToken() {
return KeywordToken;
}};
});
System.register("traceur@0.0.52/src/syntax/unicode-tables", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/unicode-tables";
var idStartTable = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 442, 443, 443, 444, 447, 448, 451, 452, 659, 660, 660, 661, 687, 688, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 883, 884, 884, 886, 887, 890, 890, 891, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1599, 1600, 1600, 1601, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2417, 2418, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3653, 3654, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4348, 4349, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6210, 6211, 6211, 6212, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7287, 7288, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7467, 7468, 7530, 7531, 7543, 7544, 7544, 7545, 7578, 7579, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8472, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8494, 8494, 8495, 8500, 8501, 8504, 8505, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8578, 8579, 8580, 8581, 8584, 11264, 11310, 11312, 11358, 11360, 11387, 11388, 11389, 11390, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12293, 12294, 12294, 12295, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12347, 12347, 12348, 12348, 12353, 12438, 12443, 12444, 12445, 12446, 12447, 12447, 12449, 12538, 12540, 12542, 12543, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 40980, 40981, 40981, 40982, 42124, 42192, 42231, 42232, 42237, 42240, 42507, 42508, 42508, 42512, 42527, 42538, 42539, 42560, 42605, 42606, 42606, 42623, 42623, 42624, 42647, 42656, 42725, 42726, 42735, 42775, 42783, 42786, 42863, 42864, 42864, 42865, 42887, 42888, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43001, 43002, 43002, 43003, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43631, 43632, 43632, 43633, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43740, 43741, 43741, 43744, 43754, 43762, 43762, 43763, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65391, 65392, 65392, 65393, 65437, 65438, 65439, 65440, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66334, 66352, 66368, 66369, 66369, 66370, 66377, 66378, 66378, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66639, 66640, 66717, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68147, 68192, 68220, 68352, 68405, 68416, 68437, 68448, 68466, 68608, 68680, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 70019, 70066, 70081, 70084, 71296, 71338, 73728, 74606, 74752, 74850, 77824, 78894, 92160, 92728, 93952, 94020, 94032, 94032, 94099, 94111, 110592, 110593, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 194560, 195101];
var idContinueTable = [183, 183, 768, 879, 903, 903, 1155, 1159, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1552, 1562, 1611, 1631, 1632, 1641, 1648, 1648, 1750, 1756, 1759, 1764, 1767, 1768, 1770, 1773, 1776, 1785, 1809, 1809, 1840, 1866, 1958, 1968, 1984, 1993, 2027, 2035, 2070, 2073, 2075, 2083, 2085, 2087, 2089, 2093, 2137, 2139, 2276, 2302, 2304, 2306, 2307, 2307, 2362, 2362, 2363, 2363, 2364, 2364, 2366, 2368, 2369, 2376, 2377, 2380, 2381, 2381, 2382, 2383, 2385, 2391, 2402, 2403, 2406, 2415, 2433, 2433, 2434, 2435, 2492, 2492, 2494, 2496, 2497, 2500, 2503, 2504, 2507, 2508, 2509, 2509, 2519, 2519, 2530, 2531, 2534, 2543, 2561, 2562, 2563, 2563, 2620, 2620, 2622, 2624, 2625, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2662, 2671, 2672, 2673, 2677, 2677, 2689, 2690, 2691, 2691, 2748, 2748, 2750, 2752, 2753, 2757, 2759, 2760, 2761, 2761, 2763, 2764, 2765, 2765, 2786, 2787, 2790, 2799, 2817, 2817, 2818, 2819, 2876, 2876, 2878, 2878, 2879, 2879, 2880, 2880, 2881, 2884, 2887, 2888, 2891, 2892, 2893, 2893, 2902, 2902, 2903, 2903, 2914, 2915, 2918, 2927, 2946, 2946, 3006, 3007, 3008, 3008, 3009, 3010, 3014, 3016, 3018, 3020, 3021, 3021, 3031, 3031, 3046, 3055, 3073, 3075, 3134, 3136, 3137, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3170, 3171, 3174, 3183, 3202, 3203, 3260, 3260, 3262, 3262, 3263, 3263, 3264, 3268, 3270, 3270, 3271, 3272, 3274, 3275, 3276, 3277, 3285, 3286, 3298, 3299, 3302, 3311, 3330, 3331, 3390, 3392, 3393, 3396, 3398, 3400, 3402, 3404, 3405, 3405, 3415, 3415, 3426, 3427, 3430, 3439, 3458, 3459, 3530, 3530, 3535, 3537, 3538, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3633, 3633, 3636, 3642, 3655, 3662, 3664, 3673, 3761, 3761, 3764, 3769, 3771, 3772, 3784, 3789, 3792, 3801, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3903, 3953, 3966, 3967, 3967, 3968, 3972, 3974, 3975, 3981, 3991, 3993, 4028, 4038, 4038, 4139, 4140, 4141, 4144, 4145, 4145, 4146, 4151, 4152, 4152, 4153, 4154, 4155, 4156, 4157, 4158, 4160, 4169, 4182, 4183, 4184, 4185, 4190, 4192, 4194, 4196, 4199, 4205, 4209, 4212, 4226, 4226, 4227, 4228, 4229, 4230, 4231, 4236, 4237, 4237, 4239, 4239, 4240, 4249, 4250, 4252, 4253, 4253, 4957, 4959, 4969, 4977, 5906, 5908, 5938, 5940, 5970, 5971, 6002, 6003, 6068, 6069, 6070, 6070, 6071, 6077, 6078, 6085, 6086, 6086, 6087, 6088, 6089, 6099, 6109, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6313, 6313, 6432, 6434, 6435, 6438, 6439, 6440, 6441, 6443, 6448, 6449, 6450, 6450, 6451, 6456, 6457, 6459, 6470, 6479, 6576, 6592, 6600, 6601, 6608, 6617, 6618, 6618, 6679, 6680, 6681, 6683, 6741, 6741, 6742, 6742, 6743, 6743, 6744, 6750, 6752, 6752, 6753, 6753, 6754, 6754, 6755, 6756, 6757, 6764, 6765, 6770, 6771, 6780, 6783, 6783, 6784, 6793, 6800, 6809, 6912, 6915, 6916, 6916, 6964, 6964, 6965, 6965, 6966, 6970, 6971, 6971, 6972, 6972, 6973, 6977, 6978, 6978, 6979, 6980, 6992, 7001, 7019, 7027, 7040, 7041, 7042, 7042, 7073, 7073, 7074, 7077, 7078, 7079, 7080, 7081, 7082, 7082, 7083, 7083, 7084, 7085, 7088, 7097, 7142, 7142, 7143, 7143, 7144, 7145, 7146, 7148, 7149, 7149, 7150, 7150, 7151, 7153, 7154, 7155, 7204, 7211, 7212, 7219, 7220, 7221, 7222, 7223, 7232, 7241, 7248, 7257, 7376, 7378, 7380, 7392, 7393, 7393, 7394, 7400, 7405, 7405, 7410, 7411, 7412, 7412, 7616, 7654, 7676, 7679, 8255, 8256, 8276, 8276, 8400, 8412, 8417, 8417, 8421, 8432, 11503, 11505, 11647, 11647, 11744, 11775, 12330, 12333, 12334, 12335, 12441, 12442, 42528, 42537, 42607, 42607, 42612, 42621, 42655, 42655, 42736, 42737, 43010, 43010, 43014, 43014, 43019, 43019, 43043, 43044, 43045, 43046, 43047, 43047, 43136, 43137, 43188, 43203, 43204, 43204, 43216, 43225, 43232, 43249, 43264, 43273, 43302, 43309, 43335, 43345, 43346, 43347, 43392, 43394, 43395, 43395, 43443, 43443, 43444, 43445, 43446, 43449, 43450, 43451, 43452, 43452, 43453, 43456, 43472, 43481, 43561, 43566, 43567, 43568, 43569, 43570, 43571, 43572, 43573, 43574, 43587, 43587, 43596, 43596, 43597, 43597, 43600, 43609, 43643, 43643, 43696, 43696, 43698, 43700, 43703, 43704, 43710, 43711, 43713, 43713, 43755, 43755, 43756, 43757, 43758, 43759, 43765, 43765, 43766, 43766, 44003, 44004, 44005, 44005, 44006, 44007, 44008, 44008, 44009, 44010, 44012, 44012, 44013, 44013, 44016, 44025, 64286, 64286, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65296, 65305, 65343, 65343, 66045, 66045, 66720, 66729, 68097, 68099, 68101, 68102, 68108, 68111, 68152, 68154, 68159, 68159, 69632, 69632, 69633, 69633, 69634, 69634, 69688, 69702, 69734, 69743, 69760, 69761, 69762, 69762, 69808, 69810, 69811, 69814, 69815, 69816, 69817, 69818, 69872, 69881, 69888, 69890, 69927, 69931, 69932, 69932, 69933, 69940, 69942, 69951, 70016, 70017, 70018, 70018, 70067, 70069, 70070, 70078, 70079, 70080, 70096, 70105, 71339, 71339, 71340, 71340, 71341, 71341, 71342, 71343, 71344, 71349, 71350, 71350, 71351, 71351, 71360, 71369, 94033, 94078, 94095, 94098, 119141, 119142, 119143, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 120782, 120831, 917760, 917999];
return {
get idStartTable() {
return idStartTable;
},
get idContinueTable() {
return idContinueTable;
}
};
});
System.register("traceur@0.0.52/src/syntax/Scanner", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/Scanner";
var IdentifierToken = System.get("traceur@0.0.52/src/syntax/IdentifierToken").IdentifierToken;
var KeywordToken = System.get("traceur@0.0.52/src/syntax/KeywordToken").KeywordToken;
var LiteralToken = System.get("traceur@0.0.52/src/syntax/LiteralToken").LiteralToken;
var Token = System.get("traceur@0.0.52/src/syntax/Token").Token;
var getKeywordType = System.get("traceur@0.0.52/src/syntax/Keywords").getKeywordType;
var $__123 = System.get("traceur@0.0.52/src/syntax/unicode-tables"),
idContinueTable = $__123.idContinueTable,
idStartTable = $__123.idStartTable;
var $__124 = System.get("traceur@0.0.52/src/Options"),
options = $__124.options,
parseOptions = $__124.parseOptions;
var $__125 = System.get("traceur@0.0.52/src/syntax/TokenType"),
AMPERSAND = $__125.AMPERSAND,
AMPERSAND_EQUAL = $__125.AMPERSAND_EQUAL,
AND = $__125.AND,
ARROW = $__125.ARROW,
AT = $__125.AT,
BANG = $__125.BANG,
BAR = $__125.BAR,
BAR_EQUAL = $__125.BAR_EQUAL,
CARET = $__125.CARET,
CARET_EQUAL = $__125.CARET_EQUAL,
CLOSE_ANGLE = $__125.CLOSE_ANGLE,
CLOSE_CURLY = $__125.CLOSE_CURLY,
CLOSE_PAREN = $__125.CLOSE_PAREN,
CLOSE_SQUARE = $__125.CLOSE_SQUARE,
COLON = $__125.COLON,
COMMA = $__125.COMMA,
DOT_DOT_DOT = $__125.DOT_DOT_DOT,
END_OF_FILE = $__125.END_OF_FILE,
EQUAL = $__125.EQUAL,
EQUAL_EQUAL = $__125.EQUAL_EQUAL,
EQUAL_EQUAL_EQUAL = $__125.EQUAL_EQUAL_EQUAL,
ERROR = $__125.ERROR,
GREATER_EQUAL = $__125.GREATER_EQUAL,
LEFT_SHIFT = $__125.LEFT_SHIFT,
LEFT_SHIFT_EQUAL = $__125.LEFT_SHIFT_EQUAL,
LESS_EQUAL = $__125.LESS_EQUAL,
MINUS = $__125.MINUS,
MINUS_EQUAL = $__125.MINUS_EQUAL,
MINUS_MINUS = $__125.MINUS_MINUS,
NO_SUBSTITUTION_TEMPLATE = $__125.NO_SUBSTITUTION_TEMPLATE,
NOT_EQUAL = $__125.NOT_EQUAL,
NOT_EQUAL_EQUAL = $__125.NOT_EQUAL_EQUAL,
NUMBER = $__125.NUMBER,
OPEN_ANGLE = $__125.OPEN_ANGLE,
OPEN_CURLY = $__125.OPEN_CURLY,
OPEN_PAREN = $__125.OPEN_PAREN,
OPEN_SQUARE = $__125.OPEN_SQUARE,
OR = $__125.OR,
PERCENT = $__125.PERCENT,
PERCENT_EQUAL = $__125.PERCENT_EQUAL,
PERIOD = $__125.PERIOD,
PLUS = $__125.PLUS,
PLUS_EQUAL = $__125.PLUS_EQUAL,
PLUS_PLUS = $__125.PLUS_PLUS,
QUESTION = $__125.QUESTION,
REGULAR_EXPRESSION = $__125.REGULAR_EXPRESSION,
RIGHT_SHIFT = $__125.RIGHT_SHIFT,
RIGHT_SHIFT_EQUAL = $__125.RIGHT_SHIFT_EQUAL,
SEMI_COLON = $__125.SEMI_COLON,
SLASH = $__125.SLASH,
SLASH_EQUAL = $__125.SLASH_EQUAL,
STAR = $__125.STAR,
STAR_EQUAL = $__125.STAR_EQUAL,
STRING = $__125.STRING,
TEMPLATE_HEAD = $__125.TEMPLATE_HEAD,
TEMPLATE_MIDDLE = $__125.TEMPLATE_MIDDLE,
TEMPLATE_TAIL = $__125.TEMPLATE_TAIL,
TILDE = $__125.TILDE,
UNSIGNED_RIGHT_SHIFT = $__125.UNSIGNED_RIGHT_SHIFT,
UNSIGNED_RIGHT_SHIFT_EQUAL = $__125.UNSIGNED_RIGHT_SHIFT_EQUAL;
var isWhitespaceArray = [];
for (var i = 0; i < 128; i++) {
isWhitespaceArray[i] = i >= 9 && i <= 13 || i === 0x20;
}
var isWhitespaceArray = [];
for (var i = 0; i < 128; i++) {
isWhitespaceArray[i] = i >= 9 && i <= 13 || i === 0x20;
}
function isWhitespace(code) {
if (code < 128)
return isWhitespaceArray[code];
switch (code) {
case 0xA0:
case 0xFEFF:
case 0x2028:
case 0x2029:
return true;
}
return false;
}
function isLineTerminator(code) {
switch (code) {
case 10:
case 13:
case 0x2028:
case 0x2029:
return true;
}
return false;
}
function isDecimalDigit(code) {
return code >= 48 && code <= 57;
}
var isHexDigitArray = [];
for (var i = 0; i < 128; i++) {
isHexDigitArray[i] = i >= 48 && i <= 57 || i >= 65 && i <= 70 || i >= 97 && i <= 102;
}
function isHexDigit(code) {
return code < 128 && isHexDigitArray[code];
}
function isBinaryDigit(code) {
return code === 48 || code === 49;
}
function isOctalDigit(code) {
return code >= 48 && code <= 55;
}
var isIdentifierStartArray = [];
for (var i = 0; i < 128; i++) {
isIdentifierStartArray[i] = i === 36 || i >= 65 && i <= 90 || i === 95 || i >= 97 && i <= 122;
}
function isIdentifierStart(code) {
return code < 128 ? isIdentifierStartArray[code] : inTable(idStartTable, code);
}
var isIdentifierPartArray = [];
for (var i = 0; i < 128; i++) {
isIdentifierPartArray[i] = isIdentifierStart(i) || isDecimalDigit(i);
}
function isIdentifierPart(code) {
return code < 128 ? isIdentifierPartArray[code] : inTable(idStartTable, code) || inTable(idContinueTable, code) || code === 8204 || code === 8205;
}
function inTable(table, code) {
for (var i = 0; i < table.length; ) {
if (code < table[i++])
return false;
if (code <= table[i++])
return true;
}
return false;
}
function isRegularExpressionChar(code) {
switch (code) {
case 47:
return false;
case 91:
case 92:
return true;
}
return !isLineTerminator(code);
}
function isRegularExpressionFirstChar(code) {
return isRegularExpressionChar(code) && code !== 42;
}
var index,
input,
length,
token,
lastToken,
lookaheadToken,
currentCharCode,
lineNumberTable,
errorReporter,
currentParser;
var Scanner = function Scanner(reporter, file, parser) {
errorReporter = reporter;
lineNumberTable = file.lineNumberTable;
input = file.contents;
length = file.contents.length;
this.index = 0;
currentParser = parser;
};
($traceurRuntime.createClass)(Scanner, {
get lastToken() {
return lastToken;
},
getPosition: function() {
return getPosition(getOffset());
},
nextRegularExpressionLiteralToken: function() {
lastToken = nextRegularExpressionLiteralToken();
token = scanToken();
return lastToken;
},
nextTemplateLiteralToken: function() {
var t = nextTemplateLiteralToken();
token = scanToken();
return t;
},
nextToken: function() {
return nextToken();
},
peekToken: function(opt_index) {
return opt_index ? peekTokenLookahead() : peekToken();
},
peekTokenNoLineTerminator: function() {
return peekTokenNoLineTerminator();
},
isAtEnd: function() {
return isAtEnd();
},
set index(i) {
index = i;
lastToken = null;
token = null;
lookaheadToken = null;
updateCurrentCharCode();
},
get index() {
return index;
}
}, {});
function getPosition(offset) {
return lineNumberTable.getSourcePosition(offset);
}
function getTokenRange(startOffset) {
return lineNumberTable.getSourceRange(startOffset, index);
}
function getOffset() {
return token ? token.location.start.offset : index;
}
function nextRegularExpressionLiteralToken() {
var beginIndex = index - token.toString().length;
if (!(token.type == SLASH_EQUAL && currentCharCode === 47) && !skipRegularExpressionBody()) {
return new LiteralToken(REGULAR_EXPRESSION, getTokenString(beginIndex), getTokenRange(beginIndex));
}
if (currentCharCode !== 47) {
reportError('Expected \'/\' in regular expression literal');
return new LiteralToken(REGULAR_EXPRESSION, getTokenString(beginIndex), getTokenRange(beginIndex));
}
next();
while (isIdentifierPart(currentCharCode)) {
next();
}
return new LiteralToken(REGULAR_EXPRESSION, getTokenString(beginIndex), getTokenRange(beginIndex));
}
function skipRegularExpressionBody() {
if (!isRegularExpressionFirstChar(currentCharCode)) {
reportError('Expected regular expression first char');
return false;
}
while (!isAtEnd() && isRegularExpressionChar(currentCharCode)) {
if (!skipRegularExpressionChar())
return false;
}
return true;
}
function skipRegularExpressionChar() {
switch (currentCharCode) {
case 92:
return skipRegularExpressionBackslashSequence();
case 91:
return skipRegularExpressionClass();
default:
next();
return true;
}
}
function skipRegularExpressionBackslashSequence() {
next();
if (isLineTerminator(currentCharCode) || isAtEnd()) {
reportError('New line not allowed in regular expression literal');
return false;
}
next();
return true;
}
function skipRegularExpressionClass() {
next();
while (!isAtEnd() && peekRegularExpressionClassChar()) {
if (!skipRegularExpressionClassChar()) {
return false;
}
}
if (currentCharCode !== 93) {
reportError('\']\' expected');
return false;
}
next();
return true;
}
function peekRegularExpressionClassChar() {
return currentCharCode !== 93 && !isLineTerminator(currentCharCode);
}
function skipRegularExpressionClassChar() {
if (currentCharCode === 92) {
return skipRegularExpressionBackslashSequence();
}
next();
return true;
}
function skipTemplateCharacter() {
while (!isAtEnd()) {
switch (currentCharCode) {
case 96:
return;
case 92:
skipStringLiteralEscapeSequence();
break;
case 36:
var code = input.charCodeAt(index + 1);
if (code === 123)
return;
default:
next();
}
}
}
function scanTemplateStart(beginIndex) {
if (isAtEnd()) {
reportError('Unterminated template literal');
return lastToken = createToken(END_OF_FILE, beginIndex);
}
return nextTemplateLiteralTokenShared(NO_SUBSTITUTION_TEMPLATE, TEMPLATE_HEAD);
}
function nextTemplateLiteralToken() {
if (isAtEnd()) {
reportError('Expected \'}\' after expression in template literal');
return createToken(END_OF_FILE, index);
}
if (token.type !== CLOSE_CURLY) {
reportError('Expected \'}\' after expression in template literal');
return createToken(ERROR, index);
}
return nextTemplateLiteralTokenShared(TEMPLATE_TAIL, TEMPLATE_MIDDLE);
}
function nextTemplateLiteralTokenShared(endType, middleType) {
var beginIndex = index;
skipTemplateCharacter();
if (isAtEnd()) {
reportError('Unterminated template literal');
return createToken(ERROR, beginIndex);
}
var value = getTokenString(beginIndex);
switch (currentCharCode) {
case 96:
next();
return lastToken = new LiteralToken(endType, value, getTokenRange(beginIndex - 1));
case 36:
next();
next();
return lastToken = new LiteralToken(middleType, value, getTokenRange(beginIndex - 1));
}
}
function nextToken() {
var t = peekToken();
token = lookaheadToken || scanToken();
lookaheadToken = null;
lastToken = t;
return t;
}
function peekTokenNoLineTerminator() {
var t = peekToken();
var start = lastToken.location.end.offset;
var end = t.location.start.offset;
for (var i = start; i < end; i++) {
var code = input.charCodeAt(i);
if (isLineTerminator(code))
return null;
if (code === 47) {
code = input.charCodeAt(++i);
if (code === 47)
return null;
i = input.indexOf('*/', i) + 2;
}
}
return t;
}
function peekToken() {
return token || (token = scanToken());
}
function peekTokenLookahead() {
if (!token)
token = scanToken();
if (!lookaheadToken)
lookaheadToken = scanToken();
return lookaheadToken;
}
function skipWhitespace() {
while (!isAtEnd() && peekWhitespace()) {
next();
}
}
function peekWhitespace() {
return isWhitespace(currentCharCode);
}
function skipComments() {
while (skipComment()) {}
}
function skipComment() {
skipWhitespace();
var code = currentCharCode;
if (code === 47) {
code = input.charCodeAt(index + 1);
switch (code) {
case 47:
skipSingleLineComment();
return true;
case 42:
skipMultiLineComment();
return true;
}
}
return false;
}
function commentCallback(start, index) {
if (options.commentCallback)
currentParser.handleComment(lineNumberTable.getSourceRange(start, index));
}
function skipSingleLineComment() {
var start = index;
index += 2;
while (!isAtEnd() && !isLineTerminator(input.charCodeAt(index++))) {}
updateCurrentCharCode();
commentCallback(start, index);
}
function skipMultiLineComment() {
var start = index;
var i = input.indexOf('*/', index + 2);
if (i !== -1)
index = i + 2;
else
index = length;
updateCurrentCharCode();
commentCallback(start, index);
}
function scanToken() {
skipComments();
var beginIndex = index;
if (isAtEnd())
return createToken(END_OF_FILE, beginIndex);
var code = currentCharCode;
next();
switch (code) {
case 123:
return createToken(OPEN_CURLY, beginIndex);
case 125:
return createToken(CLOSE_CURLY, beginIndex);
case 40:
return createToken(OPEN_PAREN, beginIndex);
case 41:
return createToken(CLOSE_PAREN, beginIndex);
case 91:
return createToken(OPEN_SQUARE, beginIndex);
case 93:
return createToken(CLOSE_SQUARE, beginIndex);
case 46:
switch (currentCharCode) {
case 46:
if (input.charCodeAt(index + 1) === 46) {
next();
next();
return createToken(DOT_DOT_DOT, beginIndex);
}
break;
default:
if (isDecimalDigit(currentCharCode))
return scanNumberPostPeriod(beginIndex);
}
return createToken(PERIOD, beginIndex);
case 59:
return createToken(SEMI_COLON, beginIndex);
case 44:
return createToken(COMMA, beginIndex);
case 126:
return createToken(TILDE, beginIndex);
case 63:
return createToken(QUESTION, beginIndex);
case 58:
return createToken(COLON, beginIndex);
case 60:
switch (currentCharCode) {
case 60:
next();
if (currentCharCode === 61) {
next();
return createToken(LEFT_SHIFT_EQUAL, beginIndex);
}
return createToken(LEFT_SHIFT, beginIndex);
case 61:
next();
return createToken(LESS_EQUAL, beginIndex);
default:
return createToken(OPEN_ANGLE, beginIndex);
}
case 62:
switch (currentCharCode) {
case 62:
next();
switch (currentCharCode) {
case 61:
next();
return createToken(RIGHT_SHIFT_EQUAL, beginIndex);
case 62:
next();
if (currentCharCode === 61) {
next();
return createToken(UNSIGNED_RIGHT_SHIFT_EQUAL, beginIndex);
}
return createToken(UNSIGNED_RIGHT_SHIFT, beginIndex);
default:
return createToken(RIGHT_SHIFT, beginIndex);
}
case 61:
next();
return createToken(GREATER_EQUAL, beginIndex);
default:
return createToken(CLOSE_ANGLE, beginIndex);
}
case 61:
if (currentCharCode === 61) {
next();
if (currentCharCode === 61) {
next();
return createToken(EQUAL_EQUAL_EQUAL, beginIndex);
}
return createToken(EQUAL_EQUAL, beginIndex);
}
if (currentCharCode === 62) {
next();
return createToken(ARROW, beginIndex);
}
return createToken(EQUAL, beginIndex);
case 33:
if (currentCharCode === 61) {
next();
if (currentCharCode === 61) {
next();
return createToken(NOT_EQUAL_EQUAL, beginIndex);
}
return createToken(NOT_EQUAL, beginIndex);
}
return createToken(BANG, beginIndex);
case 42:
if (currentCharCode === 61) {
next();
return createToken(STAR_EQUAL, beginIndex);
}
return createToken(STAR, beginIndex);
case 37:
if (currentCharCode === 61) {
next();
return createToken(PERCENT_EQUAL, beginIndex);
}
return createToken(PERCENT, beginIndex);
case 94:
if (currentCharCode === 61) {
next();
return createToken(CARET_EQUAL, beginIndex);
}
return createToken(CARET, beginIndex);
case 47:
if (currentCharCode === 61) {
next();
return createToken(SLASH_EQUAL, beginIndex);
}
return createToken(SLASH, beginIndex);
case 43:
switch (currentCharCode) {
case 43:
next();
return createToken(PLUS_PLUS, beginIndex);
case 61:
next();
return createToken(PLUS_EQUAL, beginIndex);
default:
return createToken(PLUS, beginIndex);
}
case 45:
switch (currentCharCode) {
case 45:
next();
return createToken(MINUS_MINUS, beginIndex);
case 61:
next();
return createToken(MINUS_EQUAL, beginIndex);
default:
return createToken(MINUS, beginIndex);
}
case 38:
switch (currentCharCode) {
case 38:
next();
return createToken(AND, beginIndex);
case 61:
next();
return createToken(AMPERSAND_EQUAL, beginIndex);
default:
return createToken(AMPERSAND, beginIndex);
}
case 124:
switch (currentCharCode) {
case 124:
next();
return createToken(OR, beginIndex);
case 61:
next();
return createToken(BAR_EQUAL, beginIndex);
default:
return createToken(BAR, beginIndex);
}
case 96:
return scanTemplateStart(beginIndex);
case 64:
return createToken(AT, beginIndex);
case 48:
return scanPostZero(beginIndex);
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return scanPostDigit(beginIndex);
case 34:
case 39:
return scanStringLiteral(beginIndex, code);
default:
return scanIdentifierOrKeyword(beginIndex, code);
}
}
function scanNumberPostPeriod(beginIndex) {
skipDecimalDigits();
return scanExponentOfNumericLiteral(beginIndex);
}
function scanPostDigit(beginIndex) {
skipDecimalDigits();
return scanFractionalNumericLiteral(beginIndex);
}
function scanPostZero(beginIndex) {
switch (currentCharCode) {
case 46:
return scanFractionalNumericLiteral(beginIndex);
case 88:
case 120:
next();
if (!isHexDigit(currentCharCode)) {
reportError('Hex Integer Literal must contain at least one digit');
}
skipHexDigits();
return new LiteralToken(NUMBER, getTokenString(beginIndex), getTokenRange(beginIndex));
case 66:
case 98:
if (!parseOptions.numericLiterals)
break;
next();
if (!isBinaryDigit(currentCharCode)) {
reportError('Binary Integer Literal must contain at least one digit');
}
skipBinaryDigits();
return new LiteralToken(NUMBER, getTokenString(beginIndex), getTokenRange(beginIndex));
case 79:
case 111:
if (!parseOptions.numericLiterals)
break;
next();
if (!isOctalDigit(currentCharCode)) {
reportError('Octal Integer Literal must contain at least one digit');
}
skipOctalDigits();
return new LiteralToken(NUMBER, getTokenString(beginIndex), getTokenRange(beginIndex));
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return scanPostDigit(beginIndex);
}
return new LiteralToken(NUMBER, getTokenString(beginIndex), getTokenRange(beginIndex));
}
function createToken(type, beginIndex) {
return new Token(type, getTokenRange(beginIndex));
}
function readUnicodeEscapeSequence() {
var beginIndex = index;
if (currentCharCode === 117) {
next();
if (skipHexDigit() && skipHexDigit() && skipHexDigit() && skipHexDigit()) {
return parseInt(getTokenString(beginIndex + 1), 16);
}
}
reportError('Invalid unicode escape sequence in identifier', beginIndex - 1);
return 0;
}
function scanIdentifierOrKeyword(beginIndex, code) {
var escapedCharCodes;
if (code === 92) {
code = readUnicodeEscapeSequence();
escapedCharCodes = [code];
}
if (!isIdentifierStart(code)) {
reportError(("Character code '" + code + "' is not a valid identifier start char"), beginIndex);
return createToken(ERROR, beginIndex);
}
for (; ; ) {
code = currentCharCode;
if (isIdentifierPart(code)) {
next();
} else if (code === 92) {
next();
code = readUnicodeEscapeSequence();
if (!escapedCharCodes)
escapedCharCodes = [];
escapedCharCodes.push(code);
if (!isIdentifierPart(code))
return createToken(ERROR, beginIndex);
} else {
break;
}
}
var value = input.slice(beginIndex, index);
var keywordType = getKeywordType(value);
if (keywordType)
return new KeywordToken(value, keywordType, getTokenRange(beginIndex));
if (escapedCharCodes) {
var i = 0;
value = value.replace(/\\u..../g, function(s) {
return String.fromCharCode(escapedCharCodes[i++]);
});
}
return new IdentifierToken(getTokenRange(beginIndex), value);
}
function scanStringLiteral(beginIndex, terminator) {
while (peekStringLiteralChar(terminator)) {
if (!skipStringLiteralChar()) {
return new LiteralToken(STRING, getTokenString(beginIndex), getTokenRange(beginIndex));
}
}
if (currentCharCode !== terminator) {
reportError('Unterminated String Literal', beginIndex);
} else {
next();
}
return new LiteralToken(STRING, getTokenString(beginIndex), getTokenRange(beginIndex));
}
function getTokenString(beginIndex) {
return input.substring(beginIndex, index);
}
function peekStringLiteralChar(terminator) {
return !isAtEnd() && currentCharCode !== terminator && !isLineTerminator(currentCharCode);
}
function skipStringLiteralChar() {
if (currentCharCode === 92) {
return skipStringLiteralEscapeSequence();
}
next();
return true;
}
function skipStringLiteralEscapeSequence() {
next();
if (isAtEnd()) {
reportError('Unterminated string literal escape sequence');
return false;
}
if (isLineTerminator(currentCharCode)) {
skipLineTerminator();
return true;
}
var code = currentCharCode;
next();
switch (code) {
case 39:
case 34:
case 92:
case 98:
case 102:
case 110:
case 114:
case 116:
case 118:
case 48:
return true;
case 120:
return skipHexDigit() && skipHexDigit();
case 117:
return skipHexDigit() && skipHexDigit() && skipHexDigit() && skipHexDigit();
default:
return true;
}
}
function skipHexDigit() {
if (!isHexDigit(currentCharCode)) {
reportError('Hex digit expected');
return false;
}
next();
return true;
}
function skipLineTerminator() {
var first = currentCharCode;
next();
if (first === 13 && currentCharCode === 10) {
next();
}
}
function scanFractionalNumericLiteral(beginIndex) {
if (currentCharCode === 46) {
next();
skipDecimalDigits();
}
return scanExponentOfNumericLiteral(beginIndex);
}
function scanExponentOfNumericLiteral(beginIndex) {
switch (currentCharCode) {
case 101:
case 69:
next();
switch (currentCharCode) {
case 43:
case 45:
next();
break;
}
if (!isDecimalDigit(currentCharCode)) {
reportError('Exponent part must contain at least one digit');
}
skipDecimalDigits();
break;
default:
break;
}
return new LiteralToken(NUMBER, getTokenString(beginIndex), getTokenRange(beginIndex));
}
function skipDecimalDigits() {
while (isDecimalDigit(currentCharCode)) {
next();
}
}
function skipHexDigits() {
while (isHexDigit(currentCharCode)) {
next();
}
}
function skipBinaryDigits() {
while (isBinaryDigit(currentCharCode)) {
next();
}
}
function skipOctalDigits() {
while (isOctalDigit(currentCharCode)) {
next();
}
}
function isAtEnd() {
return index === length;
}
function next() {
index++;
updateCurrentCharCode();
}
function updateCurrentCharCode() {
currentCharCode = input.charCodeAt(index);
}
function reportError(message) {
var indexArg = arguments[1] !== (void 0) ? arguments[1] : index;
var position = getPosition(indexArg);
errorReporter.reportError(position, message);
}
return {
get isWhitespace() {
return isWhitespace;
},
get isLineTerminator() {
return isLineTerminator;
},
get isIdentifierPart() {
return isIdentifierPart;
},
get Scanner() {
return Scanner;
}
};
});
System.register("traceur@0.0.52/src/syntax/Parser", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/Parser";
var FindVisitor = System.get("traceur@0.0.52/src/codegeneration/FindVisitor").FindVisitor;
var IdentifierToken = System.get("traceur@0.0.52/src/syntax/IdentifierToken").IdentifierToken;
var $__129 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
ARRAY_LITERAL_EXPRESSION = $__129.ARRAY_LITERAL_EXPRESSION,
BINDING_IDENTIFIER = $__129.BINDING_IDENTIFIER,
CALL_EXPRESSION = $__129.CALL_EXPRESSION,
COMPUTED_PROPERTY_NAME = $__129.COMPUTED_PROPERTY_NAME,
COVER_FORMALS = $__129.COVER_FORMALS,
FORMAL_PARAMETER_LIST = $__129.FORMAL_PARAMETER_LIST,
IDENTIFIER_EXPRESSION = $__129.IDENTIFIER_EXPRESSION,
LITERAL_PROPERTY_NAME = $__129.LITERAL_PROPERTY_NAME,
OBJECT_LITERAL_EXPRESSION = $__129.OBJECT_LITERAL_EXPRESSION,
REST_PARAMETER = $__129.REST_PARAMETER,
SYNTAX_ERROR_TREE = $__129.SYNTAX_ERROR_TREE;
var $__130 = System.get("traceur@0.0.52/src/syntax/PredefinedName"),
AS = $__130.AS,
ASYNC = $__130.ASYNC,
AWAIT = $__130.AWAIT,
FROM = $__130.FROM,
GET = $__130.GET,
MODULE = $__130.MODULE,
OF = $__130.OF,
SET = $__130.SET;
var SyntaxErrorReporter = System.get("traceur@0.0.52/src/util/SyntaxErrorReporter").SyntaxErrorReporter;
var Scanner = System.get("traceur@0.0.52/src/syntax/Scanner").Scanner;
var SourceRange = System.get("traceur@0.0.52/src/util/SourceRange").SourceRange;
var StrictParams = System.get("traceur@0.0.52/src/staticsemantics/StrictParams").StrictParams;
var $__135 = System.get("traceur@0.0.52/src/syntax/Token"),
Token = $__135.Token,
isAssignmentOperator = $__135.isAssignmentOperator;
var getKeywordType = System.get("traceur@0.0.52/src/syntax/Keywords").getKeywordType;
var $__137 = System.get("traceur@0.0.52/src/Options"),
parseOptions = $__137.parseOptions,
options = $__137.options;
var $__138 = System.get("traceur@0.0.52/src/syntax/TokenType"),
AMPERSAND = $__138.AMPERSAND,
AND = $__138.AND,
ARROW = $__138.ARROW,
AT = $__138.AT,
BANG = $__138.BANG,
BAR = $__138.BAR,
BREAK = $__138.BREAK,
CARET = $__138.CARET,
CASE = $__138.CASE,
CATCH = $__138.CATCH,
CLASS = $__138.CLASS,
CLOSE_ANGLE = $__138.CLOSE_ANGLE,
CLOSE_CURLY = $__138.CLOSE_CURLY,
CLOSE_PAREN = $__138.CLOSE_PAREN,
CLOSE_SQUARE = $__138.CLOSE_SQUARE,
COLON = $__138.COLON,
COMMA = $__138.COMMA,
CONST = $__138.CONST,
CONTINUE = $__138.CONTINUE,
DEBUGGER = $__138.DEBUGGER,
DEFAULT = $__138.DEFAULT,
DELETE = $__138.DELETE,
DO = $__138.DO,
DOT_DOT_DOT = $__138.DOT_DOT_DOT,
ELSE = $__138.ELSE,
END_OF_FILE = $__138.END_OF_FILE,
EQUAL = $__138.EQUAL,
EQUAL_EQUAL = $__138.EQUAL_EQUAL,
EQUAL_EQUAL_EQUAL = $__138.EQUAL_EQUAL_EQUAL,
ERROR = $__138.ERROR,
EXPORT = $__138.EXPORT,
EXTENDS = $__138.EXTENDS,
FALSE = $__138.FALSE,
FINALLY = $__138.FINALLY,
FOR = $__138.FOR,
FUNCTION = $__138.FUNCTION,
GREATER_EQUAL = $__138.GREATER_EQUAL,
IDENTIFIER = $__138.IDENTIFIER,
IF = $__138.IF,
IMPLEMENTS = $__138.IMPLEMENTS,
IMPORT = $__138.IMPORT,
IN = $__138.IN,
INSTANCEOF = $__138.INSTANCEOF,
INTERFACE = $__138.INTERFACE,
LEFT_SHIFT = $__138.LEFT_SHIFT,
LESS_EQUAL = $__138.LESS_EQUAL,
LET = $__138.LET,
MINUS = $__138.MINUS,
MINUS_MINUS = $__138.MINUS_MINUS,
NEW = $__138.NEW,
NO_SUBSTITUTION_TEMPLATE = $__138.NO_SUBSTITUTION_TEMPLATE,
NOT_EQUAL = $__138.NOT_EQUAL,
NOT_EQUAL_EQUAL = $__138.NOT_EQUAL_EQUAL,
NULL = $__138.NULL,
NUMBER = $__138.NUMBER,
OPEN_ANGLE = $__138.OPEN_ANGLE,
OPEN_CURLY = $__138.OPEN_CURLY,
OPEN_PAREN = $__138.OPEN_PAREN,
OPEN_SQUARE = $__138.OPEN_SQUARE,
OR = $__138.OR,
PACKAGE = $__138.PACKAGE,
PERCENT = $__138.PERCENT,
PERIOD = $__138.PERIOD,
PLUS = $__138.PLUS,
PLUS_PLUS = $__138.PLUS_PLUS,
PRIVATE = $__138.PRIVATE,
PROTECTED = $__138.PROTECTED,
PUBLIC = $__138.PUBLIC,
QUESTION = $__138.QUESTION,
RETURN = $__138.RETURN,
RIGHT_SHIFT = $__138.RIGHT_SHIFT,
SEMI_COLON = $__138.SEMI_COLON,
SLASH = $__138.SLASH,
SLASH_EQUAL = $__138.SLASH_EQUAL,
STAR = $__138.STAR,
STATIC = $__138.STATIC,
STRING = $__138.STRING,
SUPER = $__138.SUPER,
SWITCH = $__138.SWITCH,
TEMPLATE_HEAD = $__138.TEMPLATE_HEAD,
TEMPLATE_TAIL = $__138.TEMPLATE_TAIL,
THIS = $__138.THIS,
THROW = $__138.THROW,
TILDE = $__138.TILDE,
TRUE = $__138.TRUE,
TRY = $__138.TRY,
TYPEOF = $__138.TYPEOF,
UNSIGNED_RIGHT_SHIFT = $__138.UNSIGNED_RIGHT_SHIFT,
VAR = $__138.VAR,
VOID = $__138.VOID,
WHILE = $__138.WHILE,
WITH = $__138.WITH,
YIELD = $__138.YIELD;
var $__139 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
ArgumentList = $__139.ArgumentList,
ArrayComprehension = $__139.ArrayComprehension,
ArrayLiteralExpression = $__139.ArrayLiteralExpression,
ArrayPattern = $__139.ArrayPattern,
ArrowFunctionExpression = $__139.ArrowFunctionExpression,
AssignmentElement = $__139.AssignmentElement,
AwaitExpression = $__139.AwaitExpression,
BinaryExpression = $__139.BinaryExpression,
BindingElement = $__139.BindingElement,
BindingIdentifier = $__139.BindingIdentifier,
Block = $__139.Block,
BreakStatement = $__139.BreakStatement,
CallExpression = $__139.CallExpression,
CaseClause = $__139.CaseClause,
Catch = $__139.Catch,
ClassDeclaration = $__139.ClassDeclaration,
ClassExpression = $__139.ClassExpression,
CommaExpression = $__139.CommaExpression,
ComprehensionFor = $__139.ComprehensionFor,
ComprehensionIf = $__139.ComprehensionIf,
ComputedPropertyName = $__139.ComputedPropertyName,
ConditionalExpression = $__139.ConditionalExpression,
ContinueStatement = $__139.ContinueStatement,
CoverFormals = $__139.CoverFormals,
CoverInitializedName = $__139.CoverInitializedName,
DebuggerStatement = $__139.DebuggerStatement,
Annotation = $__139.Annotation,
DefaultClause = $__139.DefaultClause,
DoWhileStatement = $__139.DoWhileStatement,
EmptyStatement = $__139.EmptyStatement,
ExportDeclaration = $__139.ExportDeclaration,
ExportDefault = $__139.ExportDefault,
ExportSpecifier = $__139.ExportSpecifier,
ExportSpecifierSet = $__139.ExportSpecifierSet,
ExportStar = $__139.ExportStar,
ExpressionStatement = $__139.ExpressionStatement,
Finally = $__139.Finally,
ForInStatement = $__139.ForInStatement,
ForOfStatement = $__139.ForOfStatement,
ForStatement = $__139.ForStatement,
FormalParameter = $__139.FormalParameter,
FormalParameterList = $__139.FormalParameterList,
FunctionBody = $__139.FunctionBody,
FunctionDeclaration = $__139.FunctionDeclaration,
FunctionExpression = $__139.FunctionExpression,
GeneratorComprehension = $__139.GeneratorComprehension,
GetAccessor = $__139.GetAccessor,
IdentifierExpression = $__139.IdentifierExpression,
IfStatement = $__139.IfStatement,
ImportDeclaration = $__139.ImportDeclaration,
ImportSpecifier = $__139.ImportSpecifier,
ImportSpecifierSet = $__139.ImportSpecifierSet,
ImportedBinding = $__139.ImportedBinding,
LabelledStatement = $__139.LabelledStatement,
LiteralExpression = $__139.LiteralExpression,
LiteralPropertyName = $__139.LiteralPropertyName,
MemberExpression = $__139.MemberExpression,
MemberLookupExpression = $__139.MemberLookupExpression,
Module = $__139.Module,
ModuleDeclaration = $__139.ModuleDeclaration,
ModuleSpecifier = $__139.ModuleSpecifier,
NamedExport = $__139.NamedExport,
NewExpression = $__139.NewExpression,
ObjectLiteralExpression = $__139.ObjectLiteralExpression,
ObjectPattern = $__139.ObjectPattern,
ObjectPatternField = $__139.ObjectPatternField,
ParenExpression = $__139.ParenExpression,
PostfixExpression = $__139.PostfixExpression,
PredefinedType = $__139.PredefinedType,
Script = $__139.Script,
PropertyMethodAssignment = $__139.PropertyMethodAssignment,
PropertyNameAssignment = $__139.PropertyNameAssignment,
PropertyNameShorthand = $__139.PropertyNameShorthand,
RestParameter = $__139.RestParameter,
ReturnStatement = $__139.ReturnStatement,
SetAccessor = $__139.SetAccessor,
SpreadExpression = $__139.SpreadExpression,
SpreadPatternElement = $__139.SpreadPatternElement,
SuperExpression = $__139.SuperExpression,
SwitchStatement = $__139.SwitchStatement,
SyntaxErrorTree = $__139.SyntaxErrorTree,
TemplateLiteralExpression = $__139.TemplateLiteralExpression,
TemplateLiteralPortion = $__139.TemplateLiteralPortion,
TemplateSubstitution = $__139.TemplateSubstitution,
ThisExpression = $__139.ThisExpression,
ThrowStatement = $__139.ThrowStatement,
TryStatement = $__139.TryStatement,
TypeName = $__139.TypeName,
UnaryExpression = $__139.UnaryExpression,
VariableDeclaration = $__139.VariableDeclaration,
VariableDeclarationList = $__139.VariableDeclarationList,
VariableStatement = $__139.VariableStatement,
WhileStatement = $__139.WhileStatement,
WithStatement = $__139.WithStatement,
YieldExpression = $__139.YieldExpression;
var Expression = {
NO_IN: 'NO_IN',
NORMAL: 'NORMAL'
};
var DestructuringInitializer = {
REQUIRED: 'REQUIRED',
OPTIONAL: 'OPTIONAL'
};
var Initializer = {
ALLOWED: 'ALLOWED',
REQUIRED: 'REQUIRED'
};
var ValidateObjectLiteral = function ValidateObjectLiteral(tree) {
this.errorToken = null;
$traceurRuntime.superCall(this, $ValidateObjectLiteral.prototype, "constructor", [tree]);
};
var $ValidateObjectLiteral = ValidateObjectLiteral;
($traceurRuntime.createClass)(ValidateObjectLiteral, {visitCoverInitializedName: function(tree) {
this.errorToken = tree.equalToken;
this.found = true;
}}, {}, FindVisitor);
var Parser = function Parser(file) {
var errorReporter = arguments[1] !== (void 0) ? arguments[1] : new SyntaxErrorReporter();
this.errorReporter_ = errorReporter;
this.scanner_ = new Scanner(errorReporter, file, this);
this.allowYield_ = false;
this.allowAwait_ = false;
this.coverInitializedNameCount_ = 0;
this.strictMode_ = false;
this.annotations_ = [];
};
($traceurRuntime.createClass)(Parser, {
parseScript: function() {
this.strictMode_ = false;
var start = this.getTreeStartLocation_();
var scriptItemList = this.parseScriptItemList_();
this.eat_(END_OF_FILE);
return new Script(this.getTreeLocation_(start), scriptItemList);
},
parseScriptItemList_: function() {
var result = [];
var type;
var checkUseStrictDirective = true;
while ((type = this.peekType_()) !== END_OF_FILE) {
var scriptItem = this.parseScriptItem_(type, false);
if (checkUseStrictDirective) {
if (!scriptItem.isDirectivePrologue()) {
checkUseStrictDirective = false;
} else if (scriptItem.isUseStrictDirective()) {
this.strictMode_ = true;
checkUseStrictDirective = false;
}
}
result.push(scriptItem);
}
return result;
},
parseScriptItem_: function(type, allowModuleItem) {
return this.parseStatement_(type, allowModuleItem, true);
},
parseModule: function() {
var start = this.getTreeStartLocation_();
var scriptItemList = this.parseModuleItemList_();
this.eat_(END_OF_FILE);
return new Module(this.getTreeLocation_(start), scriptItemList);
},
parseModuleItemList_: function() {
this.strictMode_ = true;
var result = [];
var type;
while ((type = this.peekType_()) !== END_OF_FILE) {
var scriptItem = this.parseScriptItem_(type, true);
result.push(scriptItem);
}
return result;
},
parseModuleSpecifier_: function() {
var start = this.getTreeStartLocation_();
var token = this.eat_(STRING);
return new ModuleSpecifier(this.getTreeLocation_(start), token);
},
parseImportDeclaration_: function() {
var start = this.getTreeStartLocation_();
this.eat_(IMPORT);
var importClause = null;
if (this.peekImportClause_(this.peekType_())) {
importClause = this.parseImportClause_();
this.eatId_(FROM);
}
var moduleSpecifier = this.parseModuleSpecifier_();
this.eatPossibleImplicitSemiColon_();
return new ImportDeclaration(this.getTreeLocation_(start), importClause, moduleSpecifier);
},
peekImportClause_: function(type) {
return type === OPEN_CURLY || this.peekBindingIdentifier_(type);
},
parseImportClause_: function() {
var start = this.getTreeStartLocation_();
if (this.eatIf_(OPEN_CURLY)) {
var specifiers = [];
while (!this.peek_(CLOSE_CURLY) && !this.isAtEnd()) {
specifiers.push(this.parseImportSpecifier_());
if (!this.eatIf_(COMMA))
break;
}
this.eat_(CLOSE_CURLY);
return new ImportSpecifierSet(this.getTreeLocation_(start), specifiers);
}
var binding = this.parseBindingIdentifier_();
return new ImportedBinding(this.getTreeLocation_(start), binding);
},
parseImportSpecifier_: function() {
var start = this.getTreeStartLocation_();
var token = this.peekToken_();
var isKeyword = token.isKeyword();
var lhs = this.eatIdName_();
var rhs = null;
if (isKeyword || this.peekPredefinedString_(AS)) {
this.eatId_(AS);
rhs = this.eatId_();
}
return new ImportSpecifier(this.getTreeLocation_(start), lhs, rhs);
},
parseExportDeclaration_: function() {
var start = this.getTreeStartLocation_();
this.eat_(EXPORT);
var exportTree;
var annotations = this.popAnnotations_();
var type = this.peekType_();
switch (type) {
case CONST:
case LET:
case VAR:
exportTree = this.parseVariableStatement_();
break;
case FUNCTION:
exportTree = this.parseFunctionDeclaration_();
break;
case CLASS:
exportTree = this.parseClassDeclaration_();
break;
case DEFAULT:
exportTree = this.parseExportDefault_();
break;
case OPEN_CURLY:
case STAR:
exportTree = this.parseNamedExport_();
break;
case IDENTIFIER:
if (options.asyncFunctions && this.peekPredefinedString_(ASYNC)) {
var asyncToken = this.eatId_();
exportTree = this.parseAsyncFunctionDeclaration_(asyncToken);
break;
}
default:
return this.parseUnexpectedToken_(type);
}
return new ExportDeclaration(this.getTreeLocation_(start), exportTree, annotations);
},
parseExportDefault_: function() {
var start = this.getTreeStartLocation_();
this.eat_(DEFAULT);
var exportValue;
switch (this.peekType_()) {
case FUNCTION:
exportValue = this.parseFunctionDeclaration_();
break;
case CLASS:
if (parseOptions.classes) {
exportValue = this.parseClassDeclaration_();
break;
}
default:
exportValue = this.parseAssignmentExpression();
this.eatPossibleImplicitSemiColon_();
}
return new ExportDefault(this.getTreeLocation_(start), exportValue);
},
parseNamedExport_: function() {
var start = this.getTreeStartLocation_();
var specifierSet,
expression = null;
if (this.peek_(OPEN_CURLY)) {
specifierSet = this.parseExportSpecifierSet_();
if (this.peekPredefinedString_(FROM)) {
this.eatId_(FROM);
expression = this.parseModuleSpecifier_();
} else {
this.validateExportSpecifierSet_(specifierSet);
}
} else {
this.eat_(STAR);
specifierSet = new ExportStar(this.getTreeLocation_(start));
this.eatId_(FROM);
expression = this.parseModuleSpecifier_();
}
this.eatPossibleImplicitSemiColon_();
return new NamedExport(this.getTreeLocation_(start), expression, specifierSet);
},
parseExportSpecifierSet_: function() {
var start = this.getTreeStartLocation_();
this.eat_(OPEN_CURLY);
var specifiers = [this.parseExportSpecifier_()];
while (this.eatIf_(COMMA)) {
if (this.peek_(CLOSE_CURLY))
break;
specifiers.push(this.parseExportSpecifier_());
}
this.eat_(CLOSE_CURLY);
return new ExportSpecifierSet(this.getTreeLocation_(start), specifiers);
},
parseExportSpecifier_: function() {
var start = this.getTreeStartLocation_();
var lhs = this.eatIdName_();
var rhs = null;
if (this.peekPredefinedString_(AS)) {
this.eatId_();
rhs = this.eatIdName_();
}
return new ExportSpecifier(this.getTreeLocation_(start), lhs, rhs);
},
validateExportSpecifierSet_: function(tree) {
for (var i = 0; i < tree.specifiers.length; i++) {
var specifier = tree.specifiers[i];
if (getKeywordType(specifier.lhs.value)) {
this.reportError_(specifier.lhs.location, ("Unexpected token " + specifier.lhs.value));
}
}
},
peekId_: function(type) {
if (type === IDENTIFIER)
return true;
if (this.strictMode_)
return false;
return this.peekToken_().isStrictKeyword();
},
peekIdName_: function(token) {
return token.type === IDENTIFIER || token.isKeyword();
},
parseClassShared_: function(constr) {
var start = this.getTreeStartLocation_();
var strictMode = this.strictMode_;
this.strictMode_ = true;
this.eat_(CLASS);
var name = null;
var annotations = [];
if (constr == ClassDeclaration || !this.peek_(EXTENDS) && !this.peek_(OPEN_CURLY)) {
name = this.parseBindingIdentifier_();
annotations = this.popAnnotations_();
}
var superClass = null;
if (this.eatIf_(EXTENDS)) {
superClass = this.parseAssignmentExpression();
}
this.eat_(OPEN_CURLY);
var elements = this.parseClassElements_();
this.eat_(CLOSE_CURLY);
this.strictMode_ = strictMode;
return new constr(this.getTreeLocation_(start), name, superClass, elements, annotations);
},
parseClassDeclaration_: function() {
return this.parseClassShared_(ClassDeclaration);
},
parseClassExpression_: function() {
return this.parseClassShared_(ClassExpression);
},
parseClassElements_: function() {
var result = [];
while (true) {
var type = this.peekType_();
if (type === SEMI_COLON) {
this.nextToken_();
} else if (this.peekClassElement_(this.peekType_())) {
result.push(this.parseClassElement_());
} else {
break;
}
}
return result;
},
peekClassElement_: function(type) {
return this.peekPropertyName_(type) || type === STAR && parseOptions.generators || type === AT && parseOptions.annotations;
},
parsePropertyName_: function() {
if (this.peek_(OPEN_SQUARE))
return this.parseComputedPropertyName_();
return this.parseLiteralPropertyName_();
},
parseLiteralPropertyName_: function() {
var start = this.getTreeStartLocation_();
var token = this.nextToken_();
return new LiteralPropertyName(this.getTreeLocation_(start), token);
},
parseComputedPropertyName_: function() {
var start = this.getTreeStartLocation_();
this.eat_(OPEN_SQUARE);
var expression = this.parseAssignmentExpression();
this.eat_(CLOSE_SQUARE);
return new ComputedPropertyName(this.getTreeLocation_(start), expression);
},
parseStatement: function() {
return this.parseStatement_(this.peekType_(), false, false);
},
parseStatement_: function(type, allowModuleItem, allowScriptItem) {
switch (type) {
case RETURN:
return this.parseReturnStatement_();
case CONST:
case LET:
if (!parseOptions.blockBinding)
break;
case VAR:
return this.parseVariableStatement_();
case IF:
return this.parseIfStatement_();
case FOR:
return this.parseForStatement_();
case BREAK:
return this.parseBreakStatement_();
case SWITCH:
return this.parseSwitchStatement_();
case THROW:
return this.parseThrowStatement_();
case WHILE:
return this.parseWhileStatement_();
case FUNCTION:
return this.parseFunctionDeclaration_();
case AT:
if (parseOptions.annotations)
return this.parseAnnotatedDeclarations_(allowModuleItem, allowScriptItem);
break;
case CLASS:
if (parseOptions.classes)
return this.parseClassDeclaration_();
break;
case CONTINUE:
return this.parseContinueStatement_();
case DEBUGGER:
return this.parseDebuggerStatement_();
case DO:
return this.parseDoWhileStatement_();
case EXPORT:
if (allowModuleItem && parseOptions.modules)
return this.parseExportDeclaration_();
break;
case IMPORT:
if (allowScriptItem && parseOptions.modules)
return this.parseImportDeclaration_();
break;
case OPEN_CURLY:
return this.parseBlock_();
case SEMI_COLON:
return this.parseEmptyStatement_();
case TRY:
return this.parseTryStatement_();
case WITH:
return this.parseWithStatement_();
}
return this.parseFallThroughStatement_(allowScriptItem);
},
parseFunctionDeclaration_: function() {
return this.parseFunction_(FunctionDeclaration);
},
parseFunctionExpression_: function() {
return this.parseFunction_(FunctionExpression);
},
parseAsyncFunctionDeclaration_: function(asyncToken) {
return this.parseAsyncFunction_(asyncToken, FunctionDeclaration);
},
parseAsyncFunctionExpression_: function(asyncToken) {
return this.parseAsyncFunction_(asyncToken, FunctionExpression);
},
parseAsyncFunction_: function(asyncToken, ctor) {
var start = asyncToken.location.start;
this.eat_(FUNCTION);
return this.parseFunction2_(start, asyncToken, ctor);
},
parseFunction_: function(ctor) {
var start = this.getTreeStartLocation_();
this.eat_(FUNCTION);
var functionKind = null;
if (parseOptions.generators && this.peek_(STAR))
functionKind = this.eat_(STAR);
return this.parseFunction2_(start, functionKind, ctor);
},
parseFunction2_: function(start, functionKind, ctor) {
var name = null;
var annotations = [];
if (ctor === FunctionDeclaration || this.peekBindingIdentifier_(this.peekType_())) {
name = this.parseBindingIdentifier_();
annotations = this.popAnnotations_();
}
this.eat_(OPEN_PAREN);
var parameters = this.parseFormalParameters_();
this.eat_(CLOSE_PAREN);
var typeAnnotation = this.parseTypeAnnotationOpt_();
var body = this.parseFunctionBody_(functionKind, parameters);
return new ctor(this.getTreeLocation_(start), name, functionKind, parameters, typeAnnotation, annotations, body);
},
peekRest_: function(type) {
return type === DOT_DOT_DOT && parseOptions.restParameters;
},
parseFormalParameters_: function() {
var start = this.getTreeStartLocation_();
var formals = [];
this.pushAnnotations_();
var type = this.peekType_();
if (this.peekRest_(type)) {
formals.push(this.parseFormalRestParameter_());
} else {
if (this.peekFormalParameter_(this.peekType_()))
formals.push(this.parseFormalParameter_());
while (this.eatIf_(COMMA)) {
this.pushAnnotations_();
if (this.peekRest_(this.peekType_())) {
formals.push(this.parseFormalRestParameter_());
break;
}
formals.push(this.parseFormalParameter_());
}
}
return new FormalParameterList(this.getTreeLocation_(start), formals);
},
peekFormalParameter_: function(type) {
return this.peekBindingElement_(type);
},
parseFormalParameter_: function() {
var initializerAllowed = arguments[0];
var start = this.getTreeStartLocation_();
var binding = this.parseBindingElementBinding_();
var typeAnnotation = this.parseTypeAnnotationOpt_();
var initializer = this.parseBindingElementInitializer_(initializerAllowed);
return new FormalParameter(this.getTreeLocation_(start), new BindingElement(this.getTreeLocation_(start), binding, initializer), typeAnnotation, this.popAnnotations_());
},
parseFormalRestParameter_: function() {
var start = this.getTreeStartLocation_();
var restParameter = this.parseRestParameter_();
var typeAnnotation = this.parseTypeAnnotationOpt_();
return new FormalParameter(this.getTreeLocation_(start), restParameter, typeAnnotation, this.popAnnotations_());
},
parseRestParameter_: function() {
var start = this.getTreeStartLocation_();
this.eat_(DOT_DOT_DOT);
var id = this.parseBindingIdentifier_();
return new RestParameter(this.getTreeLocation_(start), id);
},
parseFunctionBody_: function(functionKind, params) {
var start = this.getTreeStartLocation_();
this.eat_(OPEN_CURLY);
var allowYield = this.allowYield_;
var allowAwait = this.allowAwait_;
var strictMode = this.strictMode_;
this.allowYield_ = functionKind && functionKind.type === STAR;
this.allowAwait_ = functionKind && functionKind.type === IDENTIFIER && functionKind.value === ASYNC;
var result = this.parseStatementList_(!strictMode);
if (!strictMode && this.strictMode_ && params)
StrictParams.visit(params, this.errorReporter_);
this.strictMode_ = strictMode;
this.allowYield_ = allowYield;
this.allowAwait_ = allowAwait;
this.eat_(CLOSE_CURLY);
return new FunctionBody(this.getTreeLocation_(start), result);
},
parseStatements: function() {
return this.parseStatementList_(false);
},
parseStatementList_: function(checkUseStrictDirective) {
var result = [];
var type;
while ((type = this.peekType_()) !== CLOSE_CURLY && type !== END_OF_FILE) {
var statement = this.parseStatement_(type, false, false);
if (checkUseStrictDirective) {
if (!statement.isDirectivePrologue()) {
checkUseStrictDirective = false;
} else if (statement.isUseStrictDirective()) {
this.strictMode_ = true;
checkUseStrictDirective = false;
}
}
result.push(statement);
}
return result;
},
parseSpreadExpression_: function() {
if (!parseOptions.spread)
return this.parseUnexpectedToken_(DOT_DOT_DOT);
var start = this.getTreeStartLocation_();
this.eat_(DOT_DOT_DOT);
var operand = this.parseAssignmentExpression();
return new SpreadExpression(this.getTreeLocation_(start), operand);
},
parseBlock_: function() {
var start = this.getTreeStartLocation_();
this.eat_(OPEN_CURLY);
var result = this.parseStatementList_(false);
this.eat_(CLOSE_CURLY);
return new Block(this.getTreeLocation_(start), result);
},
parseVariableStatement_: function() {
var start = this.getTreeStartLocation_();
var declarations = this.parseVariableDeclarationList_();
this.checkInitializers_(declarations);
this.eatPossibleImplicitSemiColon_();
return new VariableStatement(this.getTreeLocation_(start), declarations);
},
parseVariableDeclarationList_: function() {
var expressionIn = arguments[0] !== (void 0) ? arguments[0] : Expression.NORMAL;
var initializer = arguments[1] !== (void 0) ? arguments[1] : DestructuringInitializer.REQUIRED;
var type = this.peekType_();
switch (type) {
case CONST:
case LET:
if (!parseOptions.blockBinding)
debugger;
case VAR:
this.nextToken_();
break;
default:
throw Error('unreachable');
}
var start = this.getTreeStartLocation_();
var declarations = [];
declarations.push(this.parseVariableDeclaration_(type, expressionIn, initializer));
while (this.eatIf_(COMMA)) {
declarations.push(this.parseVariableDeclaration_(type, expressionIn, initializer));
}
return new VariableDeclarationList(this.getTreeLocation_(start), type, declarations);
},
parseVariableDeclaration_: function(binding, expressionIn) {
var initializer = arguments[2] !== (void 0) ? arguments[2] : DestructuringInitializer.REQUIRED;
var initRequired = initializer !== DestructuringInitializer.OPTIONAL;
var start = this.getTreeStartLocation_();
var lvalue;
var typeAnnotation;
if (this.peekPattern_(this.peekType_())) {
lvalue = this.parseBindingPattern_();
typeAnnotation = null;
} else {
lvalue = this.parseBindingIdentifier_();
typeAnnotation = this.parseTypeAnnotationOpt_();
}
var initializer = null;
if (this.peek_(EQUAL))
initializer = this.parseInitializer_(expressionIn);
else if (lvalue.isPattern() && initRequired)
this.reportError_('destructuring must have an initializer');
return new VariableDeclaration(this.getTreeLocation_(start), lvalue, typeAnnotation, initializer);
},
parseInitializer_: function(expressionIn) {
this.eat_(EQUAL);
return this.parseAssignmentExpression(expressionIn);
},
parseInitializerOpt_: function(expressionIn) {
if (this.eatIf_(EQUAL))
return this.parseAssignmentExpression(expressionIn);
return null;
},
parseEmptyStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(SEMI_COLON);
return new EmptyStatement(this.getTreeLocation_(start));
},
parseFallThroughStatement_: function(allowScriptItem) {
var start = this.getTreeStartLocation_();
var expression;
if (parseOptions.asyncFunctions && this.peekPredefinedString_(ASYNC) && this.peek_(FUNCTION, 1)) {
var asyncToken = this.eatId_();
var functionToken = this.peekTokenNoLineTerminator_();
if (functionToken !== null)
return this.parseAsyncFunctionDeclaration_(asyncToken);
expression = new IdentifierExpression(this.getTreeLocation_(start), asyncToken);
} else {
expression = this.parseExpression();
}
if (expression.type === IDENTIFIER_EXPRESSION) {
var nameToken = expression.identifierToken;
if (this.eatIf_(COLON)) {
var statement = this.parseStatement();
return new LabelledStatement(this.getTreeLocation_(start), nameToken, statement);
}
if (allowScriptItem && nameToken.value === MODULE && parseOptions.modules) {
var token = this.peekTokenNoLineTerminator_();
if (token !== null && token.type === IDENTIFIER) {
var name = this.eatId_();
this.eatId_(FROM);
var moduleSpecifier = this.parseModuleSpecifier_();
this.eatPossibleImplicitSemiColon_();
return new ModuleDeclaration(this.getTreeLocation_(start), name, moduleSpecifier);
}
}
}
this.eatPossibleImplicitSemiColon_();
return new ExpressionStatement(this.getTreeLocation_(start), expression);
},
parseIfStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(IF);
this.eat_(OPEN_PAREN);
var condition = this.parseExpression();
this.eat_(CLOSE_PAREN);
var ifClause = this.parseStatement();
var elseClause = null;
if (this.eatIf_(ELSE)) {
elseClause = this.parseStatement();
}
return new IfStatement(this.getTreeLocation_(start), condition, ifClause, elseClause);
},
parseDoWhileStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(DO);
var body = this.parseStatement();
this.eat_(WHILE);
this.eat_(OPEN_PAREN);
var condition = this.parseExpression();
this.eat_(CLOSE_PAREN);
this.eatPossibleImplicitSemiColon_();
return new DoWhileStatement(this.getTreeLocation_(start), body, condition);
},
parseWhileStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(WHILE);
this.eat_(OPEN_PAREN);
var condition = this.parseExpression();
this.eat_(CLOSE_PAREN);
var body = this.parseStatement();
return new WhileStatement(this.getTreeLocation_(start), condition, body);
},
parseForStatement_: function() {
var $__140 = this;
var start = this.getTreeStartLocation_();
this.eat_(FOR);
this.eat_(OPEN_PAREN);
var validate = (function(variables, kind) {
if (variables.declarations.length > 1) {
$__140.reportError_(kind + ' statement may not have more than one variable declaration');
}
var declaration = variables.declarations[0];
if (declaration.lvalue.isPattern() && declaration.initializer) {
$__140.reportError_(declaration.initializer.location, ("initializer is not allowed in " + kind + " loop with pattern"));
}
});
var type = this.peekType_();
if (this.peekVariableDeclarationList_(type)) {
var variables = this.parseVariableDeclarationList_(Expression.NO_IN, DestructuringInitializer.OPTIONAL);
type = this.peekType_();
if (type === IN) {
validate(variables, 'for-in');
var declaration = variables.declarations[0];
if (parseOptions.blockBinding && (variables.declarationType == LET || variables.declarationType == CONST)) {
if (declaration.initializer != null) {
this.reportError_('let/const in for-in statement may not have initializer');
}
}
return this.parseForInStatement_(start, variables);
} else if (this.peekOf_(type)) {
validate(variables, 'for-of');
var declaration = variables.declarations[0];
if (declaration.initializer != null) {
this.reportError_('for-of statement may not have initializer');
}
return this.parseForOfStatement_(start, variables);
} else {
this.checkInitializers_(variables);
return this.parseForStatement2_(start, variables);
}
}
if (type === SEMI_COLON) {
return this.parseForStatement2_(start, null);
}
var coverInitializedNameCount = this.coverInitializedNameCount_;
var initializer = this.parseExpressionAllowPattern_(Expression.NO_IN);
type = this.peekType_();
if (initializer.isLeftHandSideExpression() && (type === IN || this.peekOf_(type))) {
initializer = this.transformLeftHandSideExpression_(initializer);
if (this.peekOf_(type))
return this.parseForOfStatement_(start, initializer);
return this.parseForInStatement_(start, initializer);
}
this.ensureNoCoverInitializedNames_(initializer, coverInitializedNameCount);
return this.parseForStatement2_(start, initializer);
},
peekOf_: function(type) {
return type === IDENTIFIER && parseOptions.forOf && this.peekToken_().value === OF;
},
parseForOfStatement_: function(start, initializer) {
this.eatId_();
var collection = this.parseExpression();
this.eat_(CLOSE_PAREN);
var body = this.parseStatement();
return new ForOfStatement(this.getTreeLocation_(start), initializer, collection, body);
},
checkInitializers_: function(variables) {
if (parseOptions.blockBinding && variables.declarationType == CONST) {
var type = variables.declarationType;
for (var i = 0; i < variables.declarations.length; i++) {
if (!this.checkInitializer_(type, variables.declarations[i])) {
break;
}
}
}
},
checkInitializer_: function(type, declaration) {
if (parseOptions.blockBinding && type == CONST && declaration.initializer == null) {
this.reportError_('const variables must have an initializer');
return false;
}
return true;
},
peekVariableDeclarationList_: function(type) {
switch (type) {
case VAR:
return true;
case CONST:
case LET:
return parseOptions.blockBinding;
default:
return false;
}
},
parseForStatement2_: function(start, initializer) {
this.eat_(SEMI_COLON);
var condition = null;
if (!this.peek_(SEMI_COLON)) {
condition = this.parseExpression();
}
this.eat_(SEMI_COLON);
var increment = null;
if (!this.peek_(CLOSE_PAREN)) {
increment = this.parseExpression();
}
this.eat_(CLOSE_PAREN);
var body = this.parseStatement();
return new ForStatement(this.getTreeLocation_(start), initializer, condition, increment, body);
},
parseForInStatement_: function(start, initializer) {
this.eat_(IN);
var collection = this.parseExpression();
this.eat_(CLOSE_PAREN);
var body = this.parseStatement();
return new ForInStatement(this.getTreeLocation_(start), initializer, collection, body);
},
parseContinueStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(CONTINUE);
var name = null;
if (!this.peekImplicitSemiColon_(this.peekType_())) {
name = this.eatIdOpt_();
}
this.eatPossibleImplicitSemiColon_();
return new ContinueStatement(this.getTreeLocation_(start), name);
},
parseBreakStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(BREAK);
var name = null;
if (!this.peekImplicitSemiColon_(this.peekType_())) {
name = this.eatIdOpt_();
}
this.eatPossibleImplicitSemiColon_();
return new BreakStatement(this.getTreeLocation_(start), name);
},
parseReturnStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(RETURN);
var expression = null;
if (!this.peekImplicitSemiColon_(this.peekType_())) {
expression = this.parseExpression();
}
this.eatPossibleImplicitSemiColon_();
return new ReturnStatement(this.getTreeLocation_(start), expression);
},
parseYieldExpression_: function() {
var start = this.getTreeStartLocation_();
this.eat_(YIELD);
var expression = null;
var isYieldFor = false;
if (!this.peekImplicitSemiColon_(this.peekType_())) {
isYieldFor = this.eatIf_(STAR);
expression = this.parseAssignmentExpression();
}
return new YieldExpression(this.getTreeLocation_(start), expression, isYieldFor);
},
parseWithStatement_: function() {
if (this.strictMode_)
this.reportError_('Strict mode code may not include a with statement');
var start = this.getTreeStartLocation_();
this.eat_(WITH);
this.eat_(OPEN_PAREN);
var expression = this.parseExpression();
this.eat_(CLOSE_PAREN);
var body = this.parseStatement();
return new WithStatement(this.getTreeLocation_(start), expression, body);
},
parseSwitchStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(SWITCH);
this.eat_(OPEN_PAREN);
var expression = this.parseExpression();
this.eat_(CLOSE_PAREN);
this.eat_(OPEN_CURLY);
var caseClauses = this.parseCaseClauses_();
this.eat_(CLOSE_CURLY);
return new SwitchStatement(this.getTreeLocation_(start), expression, caseClauses);
},
parseCaseClauses_: function() {
var foundDefaultClause = false;
var result = [];
while (true) {
var start = this.getTreeStartLocation_();
switch (this.peekType_()) {
case CASE:
this.nextToken_();
var expression = this.parseExpression();
this.eat_(COLON);
var statements = this.parseCaseStatementsOpt_();
result.push(new CaseClause(this.getTreeLocation_(start), expression, statements));
break;
case DEFAULT:
if (foundDefaultClause) {
this.reportError_('Switch statements may have at most one default clause');
} else {
foundDefaultClause = true;
}
this.nextToken_();
this.eat_(COLON);
result.push(new DefaultClause(this.getTreeLocation_(start), this.parseCaseStatementsOpt_()));
break;
default:
return result;
}
}
},
parseCaseStatementsOpt_: function() {
var result = [];
var type;
while (true) {
switch (type = this.peekType_()) {
case CASE:
case DEFAULT:
case CLOSE_CURLY:
case END_OF_FILE:
return result;
}
result.push(this.parseStatement_(type, false, false));
}
},
parseThrowStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(THROW);
var value = null;
if (!this.peekImplicitSemiColon_(this.peekType_())) {
value = this.parseExpression();
}
this.eatPossibleImplicitSemiColon_();
return new ThrowStatement(this.getTreeLocation_(start), value);
},
parseTryStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(TRY);
var body = this.parseBlock_();
var catchBlock = null;
if (this.peek_(CATCH)) {
catchBlock = this.parseCatch_();
}
var finallyBlock = null;
if (this.peek_(FINALLY)) {
finallyBlock = this.parseFinallyBlock_();
}
if (catchBlock == null && finallyBlock == null) {
this.reportError_("'catch' or 'finally' expected.");
}
return new TryStatement(this.getTreeLocation_(start), body, catchBlock, finallyBlock);
},
parseCatch_: function() {
var start = this.getTreeStartLocation_();
var catchBlock;
this.eat_(CATCH);
this.eat_(OPEN_PAREN);
var binding;
if (this.peekPattern_(this.peekType_()))
binding = this.parseBindingPattern_();
else
binding = this.parseBindingIdentifier_();
this.eat_(CLOSE_PAREN);
var catchBody = this.parseBlock_();
catchBlock = new Catch(this.getTreeLocation_(start), binding, catchBody);
return catchBlock;
},
parseFinallyBlock_: function() {
var start = this.getTreeStartLocation_();
this.eat_(FINALLY);
var finallyBlock = this.parseBlock_();
return new Finally(this.getTreeLocation_(start), finallyBlock);
},
parseDebuggerStatement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(DEBUGGER);
this.eatPossibleImplicitSemiColon_();
return new DebuggerStatement(this.getTreeLocation_(start));
},
parsePrimaryExpression_: function() {
switch (this.peekType_()) {
case CLASS:
return parseOptions.classes ? this.parseClassExpression_() : this.parseSyntaxError_('Unexpected reserved word');
case THIS:
return this.parseThisExpression_();
case IDENTIFIER:
var identifier = this.parseIdentifierExpression_();
if (parseOptions.asyncFunctions && identifier.identifierToken.value === ASYNC) {
var token = this.peekTokenNoLineTerminator_();
if (token && token.type === FUNCTION) {
var asyncToken = identifier.identifierToken;
return this.parseAsyncFunctionExpression_(asyncToken);
}
}
return identifier;
case NUMBER:
case STRING:
case TRUE:
case FALSE:
case NULL:
return this.parseLiteralExpression_();
case OPEN_SQUARE:
return this.parseArrayLiteral_();
case OPEN_CURLY:
return this.parseObjectLiteral_();
case OPEN_PAREN:
return this.parsePrimaryExpressionStartingWithParen_();
case SLASH:
case SLASH_EQUAL:
return this.parseRegularExpressionLiteral_();
case NO_SUBSTITUTION_TEMPLATE:
case TEMPLATE_HEAD:
return this.parseTemplateLiteral_(null);
case IMPLEMENTS:
case INTERFACE:
case PACKAGE:
case PRIVATE:
case PROTECTED:
case PUBLIC:
case STATIC:
case YIELD:
if (!this.strictMode_)
return this.parseIdentifierExpression_();
this.reportReservedIdentifier_(this.nextToken_());
case END_OF_FILE:
return this.parseSyntaxError_('Unexpected end of input');
default:
return this.parseUnexpectedToken_(this.peekToken_());
}
},
parseSuperExpression_: function() {
var start = this.getTreeStartLocation_();
this.eat_(SUPER);
return new SuperExpression(this.getTreeLocation_(start));
},
parseThisExpression_: function() {
var start = this.getTreeStartLocation_();
this.eat_(THIS);
return new ThisExpression(this.getTreeLocation_(start));
},
peekBindingIdentifier_: function(type) {
return this.peekId_(type);
},
parseBindingIdentifier_: function() {
var start = this.getTreeStartLocation_();
var identifier = this.eatId_();
return new BindingIdentifier(this.getTreeLocation_(start), identifier);
},
parseIdentifierExpression_: function() {
var start = this.getTreeStartLocation_();
var identifier = this.eatId_();
return new IdentifierExpression(this.getTreeLocation_(start), identifier);
},
parseIdentifierNameExpression_: function() {
var start = this.getTreeStartLocation_();
var identifier = this.eatIdName_();
return new IdentifierExpression(this.getTreeLocation_(start), identifier);
},
parseLiteralExpression_: function() {
var start = this.getTreeStartLocation_();
var literal = this.nextLiteralToken_();
return new LiteralExpression(this.getTreeLocation_(start), literal);
},
nextLiteralToken_: function() {
return this.nextToken_();
},
parseRegularExpressionLiteral_: function() {
var start = this.getTreeStartLocation_();
var literal = this.nextRegularExpressionLiteralToken_();
return new LiteralExpression(this.getTreeLocation_(start), literal);
},
peekSpread_: function(type) {
return type === DOT_DOT_DOT && parseOptions.spread;
},
parseArrayLiteral_: function() {
var start = this.getTreeStartLocation_();
var expression;
var elements = [];
this.eat_(OPEN_SQUARE);
var type = this.peekType_();
if (type === FOR && parseOptions.arrayComprehension)
return this.parseArrayComprehension_(start);
while (true) {
type = this.peekType_();
if (type === COMMA) {
expression = null;
} else if (this.peekSpread_(type)) {
expression = this.parseSpreadExpression_();
} else if (this.peekAssignmentExpression_(type)) {
expression = this.parseAssignmentExpression();
} else {
break;
}
elements.push(expression);
type = this.peekType_();
if (type !== CLOSE_SQUARE)
this.eat_(COMMA);
}
this.eat_(CLOSE_SQUARE);
return new ArrayLiteralExpression(this.getTreeLocation_(start), elements);
},
parseArrayComprehension_: function(start) {
var list = this.parseComprehensionList_();
var expression = this.parseAssignmentExpression();
this.eat_(CLOSE_SQUARE);
return new ArrayComprehension(this.getTreeLocation_(start), list, expression);
},
parseComprehensionList_: function() {
var list = [this.parseComprehensionFor_()];
while (true) {
var type = this.peekType_();
switch (type) {
case FOR:
list.push(this.parseComprehensionFor_());
break;
case IF:
list.push(this.parseComprehensionIf_());
break;
default:
return list;
}
}
},
parseComprehensionFor_: function() {
var start = this.getTreeStartLocation_();
this.eat_(FOR);
this.eat_(OPEN_PAREN);
var left = this.parseForBinding_();
this.eatId_(OF);
var iterator = this.parseExpression();
this.eat_(CLOSE_PAREN);
return new ComprehensionFor(this.getTreeLocation_(start), left, iterator);
},
parseComprehensionIf_: function() {
var start = this.getTreeStartLocation_();
this.eat_(IF);
this.eat_(OPEN_PAREN);
var expression = this.parseExpression();
this.eat_(CLOSE_PAREN);
return new ComprehensionIf(this.getTreeLocation_(start), expression);
},
parseObjectLiteral_: function() {
var start = this.getTreeStartLocation_();
var result = [];
this.eat_(OPEN_CURLY);
while (this.peekPropertyDefinition_(this.peekType_())) {
var propertyDefinition = this.parsePropertyDefinition();
result.push(propertyDefinition);
if (!this.eatIf_(COMMA))
break;
}
this.eat_(CLOSE_CURLY);
return new ObjectLiteralExpression(this.getTreeLocation_(start), result);
},
parsePropertyDefinition: function() {
var start = this.getTreeStartLocation_();
var functionKind = null;
var isStatic = false;
if (parseOptions.generators && parseOptions.propertyMethods && this.peek_(STAR)) {
return this.parseGeneratorMethod_(start, isStatic, []);
}
var token = this.peekToken_();
var name = this.parsePropertyName_();
if (parseOptions.propertyMethods && this.peek_(OPEN_PAREN))
return this.parseMethod_(start, isStatic, functionKind, name, []);
if (this.eatIf_(COLON)) {
var value = this.parseAssignmentExpression();
return new PropertyNameAssignment(this.getTreeLocation_(start), name, value);
}
var type = this.peekType_();
if (name.type === LITERAL_PROPERTY_NAME) {
var nameLiteral = name.literalToken;
if (nameLiteral.value === GET && this.peekPropertyName_(type)) {
return this.parseGetAccessor_(start, isStatic, []);
}
if (nameLiteral.value === SET && this.peekPropertyName_(type)) {
return this.parseSetAccessor_(start, isStatic, []);
}
if (parseOptions.asyncFunctions && nameLiteral.value === ASYNC && this.peekPropertyName_(type)) {
var async = nameLiteral;
var name = this.parsePropertyName_();
return this.parseMethod_(start, isStatic, async, name, []);
}
if (parseOptions.propertyNameShorthand && nameLiteral.type === IDENTIFIER || !this.strictMode_ && nameLiteral.type === YIELD) {
if (this.peek_(EQUAL)) {
token = this.nextToken_();
var coverInitializedNameCount = this.coverInitializedNameCount_;
var expr = this.parseAssignmentExpression();
this.ensureNoCoverInitializedNames_(expr, coverInitializedNameCount);
this.coverInitializedNameCount_++;
return new CoverInitializedName(this.getTreeLocation_(start), nameLiteral, token, expr);
}
if (nameLiteral.type === YIELD)
nameLiteral = new IdentifierToken(nameLiteral.location, YIELD);
return new PropertyNameShorthand(this.getTreeLocation_(start), nameLiteral);
}
if (this.strictMode_ && nameLiteral.isStrictKeyword())
this.reportReservedIdentifier_(nameLiteral);
}
if (name.type === COMPUTED_PROPERTY_NAME)
token = this.peekToken_();
return this.parseUnexpectedToken_(token);
},
parseClassElement_: function() {
var start = this.getTreeStartLocation_();
var annotations = this.parseAnnotations_();
var type = this.peekType_();
var isStatic = false,
functionKind = null;
switch (type) {
case STATIC:
var staticToken = this.nextToken_();
type = this.peekType_();
switch (type) {
case OPEN_PAREN:
var name = new LiteralPropertyName(start, staticToken);
return this.parseMethod_(start, isStatic, functionKind, name, annotations);
default:
isStatic = true;
if (type === STAR && parseOptions.generators)
return this.parseGeneratorMethod_(start, true, annotations);
return this.parseGetSetOrMethod_(start, isStatic, annotations);
}
break;
case STAR:
return this.parseGeneratorMethod_(start, isStatic, annotations);
default:
return this.parseGetSetOrMethod_(start, isStatic, annotations);
}
},
parseGeneratorMethod_: function(start, isStatic, annotations) {
var functionKind = this.eat_(STAR);
var name = this.parsePropertyName_();
return this.parseMethod_(start, isStatic, functionKind, name, annotations);
},
parseMethod_: function(start, isStatic, functionKind, name, annotations) {
this.eat_(OPEN_PAREN);
var parameterList = this.parseFormalParameters_();
this.eat_(CLOSE_PAREN);
var typeAnnotation = this.parseTypeAnnotationOpt_();
var body = this.parseFunctionBody_(functionKind, parameterList);
return new PropertyMethodAssignment(this.getTreeLocation_(start), isStatic, functionKind, name, parameterList, typeAnnotation, annotations, body);
},
parseGetSetOrMethod_: function(start, isStatic, annotations) {
var functionKind = null;
var name = this.parsePropertyName_();
var type = this.peekType_();
if (name.type === LITERAL_PROPERTY_NAME && name.literalToken.value === GET && this.peekPropertyName_(type)) {
return this.parseGetAccessor_(start, isStatic, annotations);
}
if (name.type === LITERAL_PROPERTY_NAME && name.literalToken.value === SET && this.peekPropertyName_(type)) {
return this.parseSetAccessor_(start, isStatic, annotations);
}
if (parseOptions.asyncFunctions && name.type === LITERAL_PROPERTY_NAME && name.literalToken.value === ASYNC && this.peekPropertyName_(type)) {
var async = name.literalToken;
var name = this.parsePropertyName_();
return this.parseMethod_(start, isStatic, async, name, annotations);
}
return this.parseMethod_(start, isStatic, functionKind, name, annotations);
},
parseGetAccessor_: function(start, isStatic, annotations) {
var functionKind = null;
var name = this.parsePropertyName_();
this.eat_(OPEN_PAREN);
this.eat_(CLOSE_PAREN);
var typeAnnotation = this.parseTypeAnnotationOpt_();
var body = this.parseFunctionBody_(functionKind, null);
return new GetAccessor(this.getTreeLocation_(start), isStatic, name, typeAnnotation, annotations, body);
},
parseSetAccessor_: function(start, isStatic, annotations) {
var functionKind = null;
var name = this.parsePropertyName_();
this.eat_(OPEN_PAREN);
var parameterList = this.parsePropertySetParameterList_();
this.eat_(CLOSE_PAREN);
var body = this.parseFunctionBody_(functionKind, parameterList);
return new SetAccessor(this.getTreeLocation_(start), isStatic, name, parameterList, annotations, body);
},
peekPropertyDefinition_: function(type) {
return this.peekPropertyName_(type) || type == STAR && parseOptions.propertyMethods && parseOptions.generators;
},
peekPropertyName_: function(type) {
switch (type) {
case IDENTIFIER:
case STRING:
case NUMBER:
return true;
case OPEN_SQUARE:
return parseOptions.computedPropertyNames;
default:
return this.peekToken_().isKeyword();
}
},
peekPredefinedString_: function(string) {
var token = this.peekToken_();
return token.type === IDENTIFIER && token.value === string;
},
parsePropertySetParameterList_: function() {
var start = this.getTreeStartLocation_();
var binding;
this.pushAnnotations_();
if (this.peekPattern_(this.peekType_()))
binding = this.parseBindingPattern_();
else
binding = this.parseBindingIdentifier_();
var typeAnnotation = this.parseTypeAnnotationOpt_();
var parameter = new FormalParameter(this.getTreeLocation_(start), new BindingElement(this.getTreeLocation_(start), binding, null), typeAnnotation, this.popAnnotations_());
return new FormalParameterList(parameter.location, [parameter]);
},
parsePrimaryExpressionStartingWithParen_: function() {
var start = this.getTreeStartLocation_();
this.eat_(OPEN_PAREN);
if (this.peek_(FOR) && parseOptions.generatorComprehension)
return this.parseGeneratorComprehension_(start);
return this.parseCoverFormals_(start);
},
parseSyntaxError_: function(message) {
var start = this.getTreeStartLocation_();
this.reportError_(message);
var token = this.nextToken_();
return new SyntaxErrorTree(this.getTreeLocation_(start), token, message);
},
parseUnexpectedToken_: function(name) {
return this.parseSyntaxError_(("Unexpected token " + name));
},
peekExpression_: function(type) {
switch (type) {
case NO_SUBSTITUTION_TEMPLATE:
case TEMPLATE_HEAD:
return parseOptions.templateLiterals;
case BANG:
case CLASS:
case DELETE:
case FALSE:
case FUNCTION:
case IDENTIFIER:
case MINUS:
case MINUS_MINUS:
case NEW:
case NULL:
case NUMBER:
case OPEN_CURLY:
case OPEN_PAREN:
case OPEN_SQUARE:
case PLUS:
case PLUS_PLUS:
case SLASH:
case SLASH_EQUAL:
case STRING:
case SUPER:
case THIS:
case TILDE:
case TRUE:
case TYPEOF:
case VOID:
case YIELD:
return true;
default:
return false;
}
},
parseExpression: function() {
var expressionIn = arguments[0] !== (void 0) ? arguments[0] : Expression.IN;
var coverInitializedNameCount = this.coverInitializedNameCount_;
var expression = this.parseExpressionAllowPattern_(expressionIn);
this.ensureNoCoverInitializedNames_(expression, coverInitializedNameCount);
return expression;
},
parseExpressionAllowPattern_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var expression = this.parseAssignmentExpression(expressionIn);
if (this.peek_(COMMA)) {
var expressions = [expression];
while (this.eatIf_(COMMA)) {
expressions.push(this.parseAssignmentExpression(expressionIn));
}
return new CommaExpression(this.getTreeLocation_(start), expressions);
}
return expression;
},
peekAssignmentExpression_: function(type) {
return this.peekExpression_(type);
},
parseAssignmentExpression: function() {
var expressionIn = arguments[0] !== (void 0) ? arguments[0] : Expression.NORMAL;
if (this.allowYield_ && this.peek_(YIELD))
return this.parseYieldExpression_();
var start = this.getTreeStartLocation_();
var validAsyncParen = false;
if (options.asyncFunctions && this.peekPredefinedString_(ASYNC)) {
var asyncToken = this.peekToken_();
var maybeOpenParenToken = this.peekToken_(1);
validAsyncParen = maybeOpenParenToken.type === OPEN_PAREN && asyncToken.location.end.line === maybeOpenParenToken.location.start.line;
}
var left = this.parseConditional_(expressionIn);
var type = this.peekType_();
if (options.asyncFunctions && left.type === IDENTIFIER_EXPRESSION && left.identifierToken.value === ASYNC && type === IDENTIFIER) {
if (this.peekTokenNoLineTerminator_() !== null) {
var bindingIdentifier = this.parseBindingIdentifier_();
var asyncToken = left.IdentifierToken;
return this.parseArrowFunction_(start, bindingIdentifier, asyncToken);
}
}
if (type === ARROW) {
if (left.type === COVER_FORMALS || left.type === IDENTIFIER_EXPRESSION)
return this.parseArrowFunction_(start, left, null);
if (validAsyncParen && left.type === CALL_EXPRESSION) {
var arrowToken = this.peekTokenNoLineTerminator_();
if (arrowToken !== null) {
var asyncToken = left.operand.identifierToken;
return this.parseArrowFunction_(start, left.args, asyncToken);
}
}
}
left = this.coverFormalsToParenExpression_(left);
if (this.peekAssignmentOperator_(type)) {
if (type === EQUAL)
left = this.transformLeftHandSideExpression_(left);
if (!left.isLeftHandSideExpression() && !left.isPattern()) {
this.reportError_('Left hand side of assignment must be new, call, member, function, primary expressions or destructuring pattern');
}
var operator = this.nextToken_();
var right = this.parseAssignmentExpression(expressionIn);
return new BinaryExpression(this.getTreeLocation_(start), left, operator, right);
}
return left;
},
transformLeftHandSideExpression_: function(tree) {
switch (tree.type) {
case ARRAY_LITERAL_EXPRESSION:
case OBJECT_LITERAL_EXPRESSION:
this.scanner_.index = tree.location.start.offset;
return this.parseAssignmentPattern_();
}
return tree;
},
peekAssignmentOperator_: function(type) {
return isAssignmentOperator(type);
},
parseConditional_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var condition = this.parseLogicalOR_(expressionIn);
if (this.eatIf_(QUESTION)) {
condition = this.toPrimaryExpression_(condition);
var left = this.parseAssignmentExpression();
this.eat_(COLON);
var right = this.parseAssignmentExpression(expressionIn);
return new ConditionalExpression(this.getTreeLocation_(start), condition, left, right);
}
return condition;
},
newBinaryExpression_: function(start, left, operator, right) {
left = this.toPrimaryExpression_(left);
right = this.toPrimaryExpression_(right);
return new BinaryExpression(this.getTreeLocation_(start), left, operator, right);
},
parseLogicalOR_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var left = this.parseLogicalAND_(expressionIn);
var operator;
while (operator = this.eatOpt_(OR)) {
var right = this.parseLogicalAND_(expressionIn);
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
parseLogicalAND_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var left = this.parseBitwiseOR_(expressionIn);
var operator;
while (operator = this.eatOpt_(AND)) {
var right = this.parseBitwiseOR_(expressionIn);
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
parseBitwiseOR_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var left = this.parseBitwiseXOR_(expressionIn);
var operator;
while (operator = this.eatOpt_(BAR)) {
var right = this.parseBitwiseXOR_(expressionIn);
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
parseBitwiseXOR_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var left = this.parseBitwiseAND_(expressionIn);
var operator;
while (operator = this.eatOpt_(CARET)) {
var right = this.parseBitwiseAND_(expressionIn);
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
parseBitwiseAND_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var left = this.parseEquality_(expressionIn);
var operator;
while (operator = this.eatOpt_(AMPERSAND)) {
var right = this.parseEquality_(expressionIn);
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
parseEquality_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var left = this.parseRelational_(expressionIn);
while (this.peekEqualityOperator_(this.peekType_())) {
var operator = this.nextToken_();
var right = this.parseRelational_(expressionIn);
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
peekEqualityOperator_: function(type) {
switch (type) {
case EQUAL_EQUAL:
case NOT_EQUAL:
case EQUAL_EQUAL_EQUAL:
case NOT_EQUAL_EQUAL:
return true;
}
return false;
},
parseRelational_: function(expressionIn) {
var start = this.getTreeStartLocation_();
var left = this.parseShiftExpression_();
while (this.peekRelationalOperator_(expressionIn)) {
var operator = this.nextToken_();
var right = this.parseShiftExpression_();
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
peekRelationalOperator_: function(expressionIn) {
switch (this.peekType_()) {
case OPEN_ANGLE:
case CLOSE_ANGLE:
case GREATER_EQUAL:
case LESS_EQUAL:
case INSTANCEOF:
return true;
case IN:
return expressionIn == Expression.NORMAL;
default:
return false;
}
},
parseShiftExpression_: function() {
var start = this.getTreeStartLocation_();
var left = this.parseAdditiveExpression_();
while (this.peekShiftOperator_(this.peekType_())) {
var operator = this.nextToken_();
var right = this.parseAdditiveExpression_();
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
peekShiftOperator_: function(type) {
switch (type) {
case LEFT_SHIFT:
case RIGHT_SHIFT:
case UNSIGNED_RIGHT_SHIFT:
return true;
default:
return false;
}
},
parseAdditiveExpression_: function() {
var start = this.getTreeStartLocation_();
var left = this.parseMultiplicativeExpression_();
while (this.peekAdditiveOperator_(this.peekType_())) {
var operator = this.nextToken_();
var right = this.parseMultiplicativeExpression_();
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
peekAdditiveOperator_: function(type) {
switch (type) {
case PLUS:
case MINUS:
return true;
default:
return false;
}
},
parseMultiplicativeExpression_: function() {
var start = this.getTreeStartLocation_();
var left = this.parseUnaryExpression_();
while (this.peekMultiplicativeOperator_(this.peekType_())) {
var operator = this.nextToken_();
var right = this.parseUnaryExpression_();
left = this.newBinaryExpression_(start, left, operator, right);
}
return left;
},
peekMultiplicativeOperator_: function(type) {
switch (type) {
case STAR:
case SLASH:
case PERCENT:
return true;
default:
return false;
}
},
parseUnaryExpression_: function() {
var start = this.getTreeStartLocation_();
if (this.allowAwait_ && this.peekPredefinedString_(AWAIT)) {
this.eatId_();
var operand = this.parseUnaryExpression_();
operand = this.toPrimaryExpression_(operand);
return new AwaitExpression(this.getTreeLocation_(start), operand);
}
if (this.peekUnaryOperator_(this.peekType_())) {
var operator = this.nextToken_();
var operand = this.parseUnaryExpression_();
operand = this.toPrimaryExpression_(operand);
return new UnaryExpression(this.getTreeLocation_(start), operator, operand);
}
return this.parsePostfixExpression_();
},
peekUnaryOperator_: function(type) {
switch (type) {
case DELETE:
case VOID:
case TYPEOF:
case PLUS_PLUS:
case MINUS_MINUS:
case PLUS:
case MINUS:
case TILDE:
case BANG:
return true;
default:
return false;
}
},
parsePostfixExpression_: function() {
var start = this.getTreeStartLocation_();
var operand = this.parseLeftHandSideExpression_();
while (this.peekPostfixOperator_(this.peekType_())) {
operand = this.toPrimaryExpression_(operand);
var operator = this.nextToken_();
operand = new PostfixExpression(this.getTreeLocation_(start), operand, operator);
}
return operand;
},
peekPostfixOperator_: function(type) {
switch (type) {
case PLUS_PLUS:
case MINUS_MINUS:
var token = this.peekTokenNoLineTerminator_();
return token !== null;
}
return false;
},
parseLeftHandSideExpression_: function() {
var start = this.getTreeStartLocation_();
var operand = this.parseNewExpression_();
if (!(operand instanceof NewExpression) || operand.args != null) {
loop: while (true) {
switch (this.peekType_()) {
case OPEN_PAREN:
operand = this.toPrimaryExpression_(operand);
operand = this.parseCallExpression_(start, operand);
break;
case OPEN_SQUARE:
operand = this.toPrimaryExpression_(operand);
operand = this.parseMemberLookupExpression_(start, operand);
break;
case PERIOD:
operand = this.toPrimaryExpression_(operand);
operand = this.parseMemberExpression_(start, operand);
break;
case NO_SUBSTITUTION_TEMPLATE:
case TEMPLATE_HEAD:
if (!parseOptions.templateLiterals)
break loop;
operand = this.toPrimaryExpression_(operand);
operand = this.parseTemplateLiteral_(operand);
break;
default:
break loop;
}
}
}
return operand;
},
parseMemberExpressionNoNew_: function() {
var start = this.getTreeStartLocation_();
var operand;
if (this.peekType_() === FUNCTION) {
operand = this.parseFunctionExpression_();
} else {
operand = this.parsePrimaryExpression_();
}
loop: while (true) {
switch (this.peekType_()) {
case OPEN_SQUARE:
operand = this.toPrimaryExpression_(operand);
operand = this.parseMemberLookupExpression_(start, operand);
break;
case PERIOD:
operand = this.toPrimaryExpression_(operand);
operand = this.parseMemberExpression_(start, operand);
break;
case NO_SUBSTITUTION_TEMPLATE:
case TEMPLATE_HEAD:
if (!parseOptions.templateLiterals)
break loop;
operand = this.toPrimaryExpression_(operand);
operand = this.parseTemplateLiteral_(operand);
break;
default:
break loop;
}
}
return operand;
},
parseMemberExpression_: function(start, operand) {
this.nextToken_();
var name = this.eatIdName_();
return new MemberExpression(this.getTreeLocation_(start), operand, name);
},
parseMemberLookupExpression_: function(start, operand) {
this.nextToken_();
var member = this.parseExpression();
this.eat_(CLOSE_SQUARE);
return new MemberLookupExpression(this.getTreeLocation_(start), operand, member);
},
parseCallExpression_: function(start, operand) {
var args = this.parseArguments_();
return new CallExpression(this.getTreeLocation_(start), operand, args);
},
parseNewExpression_: function() {
var operand;
switch (this.peekType_()) {
case NEW:
var start = this.getTreeStartLocation_();
this.eat_(NEW);
if (this.peek_(SUPER))
operand = this.parseSuperExpression_();
else
operand = this.toPrimaryExpression_(this.parseNewExpression_());
var args = null;
if (this.peek_(OPEN_PAREN)) {
args = this.parseArguments_();
}
return new NewExpression(this.getTreeLocation_(start), operand, args);
case SUPER:
operand = this.parseSuperExpression_();
var type = this.peekType_();
switch (type) {
case OPEN_SQUARE:
return this.parseMemberLookupExpression_(start, operand);
case PERIOD:
return this.parseMemberExpression_(start, operand);
case OPEN_PAREN:
return this.parseCallExpression_(start, operand);
default:
return this.parseUnexpectedToken_(type);
}
break;
default:
return this.parseMemberExpressionNoNew_();
}
},
parseArguments_: function() {
var start = this.getTreeStartLocation_();
var args = [];
this.eat_(OPEN_PAREN);
if (!this.peek_(CLOSE_PAREN)) {
args.push(this.parseArgument_());
while (this.eatIf_(COMMA)) {
args.push(this.parseArgument_());
}
}
this.eat_(CLOSE_PAREN);
return new ArgumentList(this.getTreeLocation_(start), args);
},
parseArgument_: function() {
if (this.peekSpread_(this.peekType_()))
return this.parseSpreadExpression_();
return this.parseAssignmentExpression();
},
parseArrowFunction_: function(start, tree, asyncToken) {
var formals;
switch (tree.type) {
case IDENTIFIER_EXPRESSION:
tree = new BindingIdentifier(tree.location, tree.identifierToken);
case BINDING_IDENTIFIER:
formals = new FormalParameterList(this.getTreeLocation_(start), [new FormalParameter(tree.location, new BindingElement(tree.location, tree, null), null, [])]);
break;
case FORMAL_PARAMETER_LIST:
formals = tree;
break;
default:
formals = this.toFormalParameters_(start, tree, asyncToken);
}
this.eat_(ARROW);
var body = this.parseConciseBody_(asyncToken);
return new ArrowFunctionExpression(this.getTreeLocation_(start), asyncToken, formals, body);
},
parseCoverFormals_: function(start) {
var expressions = [];
if (!this.peek_(CLOSE_PAREN)) {
do {
var type = this.peekType_();
if (this.peekRest_(type)) {
expressions.push(this.parseRestParameter_());
break;
} else {
expressions.push(this.parseAssignmentExpression());
}
if (this.eatIf_(COMMA))
continue;
} while (!this.peek_(CLOSE_PAREN) && !this.isAtEnd());
}
this.eat_(CLOSE_PAREN);
return new CoverFormals(this.getTreeLocation_(start), expressions);
},
ensureNoCoverInitializedNames_: function(tree, coverInitializedNameCount) {
if (coverInitializedNameCount === this.coverInitializedNameCount_)
return;
var finder = new ValidateObjectLiteral(tree);
if (finder.found) {
var token = finder.errorToken;
this.reportError_(token.location, ("Unexpected token " + token));
}
},
toPrimaryExpression_: function(tree) {
if (tree.type === COVER_FORMALS)
return this.coverFormalsToParenExpression_(tree);
return tree;
},
validateCoverFormalsAsParenExpression_: function(tree) {
for (var i = 0; i < tree.expressions.length; i++) {
if (tree.expressions[i].type === REST_PARAMETER) {
var token = new Token(DOT_DOT_DOT, tree.expressions[i].location);
this.reportError_(token.location, ("Unexpected token " + token));
return;
}
}
},
coverFormalsToParenExpression_: function(tree) {
if (tree.type === COVER_FORMALS) {
var expressions = tree.expressions;
if (expressions.length === 0) {
var message = 'Unexpected token )';
this.reportError_(tree.location, message);
} else {
this.validateCoverFormalsAsParenExpression_(tree);
var expression;
if (expressions.length > 1)
expression = new CommaExpression(expressions[0].location, expressions);
else
expression = expressions[0];
return new ParenExpression(tree.location, expression);
}
}
return tree;
},
toFormalParameters_: function(start, tree, asyncToken) {
this.scanner_.index = start.offset;
return this.parseArrowFormalParameters_(asyncToken);
},
parseArrowFormalParameters_: function(asyncToken) {
if (asyncToken)
this.eat_(IDENTIFIER);
this.eat_(OPEN_PAREN);
var parameters = this.parseFormalParameters_();
this.eat_(CLOSE_PAREN);
return parameters;
},
peekArrow_: function(type) {
return type === ARROW && parseOptions.arrowFunctions;
},
parseConciseBody_: function(asyncToken) {
if (this.peek_(OPEN_CURLY))
return this.parseFunctionBody_(asyncToken);
var allowAwait = this.allowAwait_;
this.allowAwait_ = asyncToken !== null;
var expression = this.parseAssignmentExpression();
this.allowAwait_ = allowAwait;
return expression;
},
parseGeneratorComprehension_: function(start) {
var comprehensionList = this.parseComprehensionList_();
var expression = this.parseAssignmentExpression();
this.eat_(CLOSE_PAREN);
return new GeneratorComprehension(this.getTreeLocation_(start), comprehensionList, expression);
},
parseForBinding_: function() {
if (this.peekPattern_(this.peekType_()))
return this.parseBindingPattern_();
return this.parseBindingIdentifier_();
},
peekPattern_: function(type) {
return parseOptions.destructuring && (this.peekObjectPattern_(type) || this.peekArrayPattern_(type));
},
peekArrayPattern_: function(type) {
return type === OPEN_SQUARE;
},
peekObjectPattern_: function(type) {
return type === OPEN_CURLY;
},
parseBindingPattern_: function() {
return this.parsePattern_(true);
},
parsePattern_: function(useBinding) {
if (this.peekArrayPattern_(this.peekType_()))
return this.parseArrayPattern_(useBinding);
return this.parseObjectPattern_(useBinding);
},
parseArrayBindingPattern_: function() {
return this.parseArrayPattern_(true);
},
parsePatternElement_: function(useBinding) {
return useBinding ? this.parseBindingElement_() : this.parseAssignmentElement_();
},
parsePatternRestElement_: function(useBinding) {
return useBinding ? this.parseBindingRestElement_() : this.parseAssignmentRestElement_();
},
parseArrayPattern_: function(useBinding) {
var start = this.getTreeStartLocation_();
var elements = [];
this.eat_(OPEN_SQUARE);
var type;
while ((type = this.peekType_()) !== CLOSE_SQUARE && type !== END_OF_FILE) {
this.parseElisionOpt_(elements);
if (this.peekRest_(this.peekType_())) {
elements.push(this.parsePatternRestElement_(useBinding));
break;
} else {
elements.push(this.parsePatternElement_(useBinding));
if (this.peek_(COMMA) && !this.peek_(CLOSE_SQUARE, 1)) {
this.nextToken_();
}
}
}
this.eat_(CLOSE_SQUARE);
return new ArrayPattern(this.getTreeLocation_(start), elements);
},
parseBindingElementList_: function(elements) {
this.parseElisionOpt_(elements);
elements.push(this.parseBindingElement_());
while (this.eatIf_(COMMA)) {
this.parseElisionOpt_(elements);
elements.push(this.parseBindingElement_());
}
},
parseElisionOpt_: function(elements) {
while (this.eatIf_(COMMA)) {
elements.push(null);
}
},
peekBindingElement_: function(type) {
return this.peekBindingIdentifier_(type) || this.peekPattern_(type);
},
parseBindingElement_: function() {
var initializer = arguments[0] !== (void 0) ? arguments[0] : Initializer.OPTIONAL;
var start = this.getTreeStartLocation_();
var binding = this.parseBindingElementBinding_();
var initializer = this.parseBindingElementInitializer_(initializer);
return new BindingElement(this.getTreeLocation_(start), binding, initializer);
},
parseBindingElementBinding_: function() {
if (this.peekPattern_(this.peekType_()))
return this.parseBindingPattern_();
return this.parseBindingIdentifier_();
},
parseBindingElementInitializer_: function() {
var initializer = arguments[0] !== (void 0) ? arguments[0] : Initializer.OPTIONAL;
if (this.peek_(EQUAL) || initializer === Initializer.REQUIRED) {
return this.parseInitializer_();
}
return null;
},
parseBindingRestElement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(DOT_DOT_DOT);
var identifier = this.parseBindingIdentifier_();
return new SpreadPatternElement(this.getTreeLocation_(start), identifier);
},
parseObjectPattern_: function(useBinding) {
var start = this.getTreeStartLocation_();
var elements = [];
this.eat_(OPEN_CURLY);
var type;
while ((type = this.peekType_()) !== CLOSE_CURLY && type !== END_OF_FILE) {
elements.push(this.parsePatternProperty_(useBinding));
if (!this.eatIf_(COMMA))
break;
}
this.eat_(CLOSE_CURLY);
return new ObjectPattern(this.getTreeLocation_(start), elements);
},
parsePatternProperty_: function(useBinding) {
var start = this.getTreeStartLocation_();
var name = this.parsePropertyName_();
var requireColon = name.type !== LITERAL_PROPERTY_NAME || !name.literalToken.isStrictKeyword() && name.literalToken.type !== IDENTIFIER;
if (requireColon || this.peek_(COLON)) {
this.eat_(COLON);
var element = this.parsePatternElement_(useBinding);
return new ObjectPatternField(this.getTreeLocation_(start), name, element);
}
var token = name.literalToken;
if (this.strictMode_ && token.isStrictKeyword())
this.reportReservedIdentifier_(token);
if (useBinding) {
var binding = new BindingIdentifier(name.location, token);
var initializer = this.parseInitializerOpt_(Expression.NORMAL);
return new BindingElement(this.getTreeLocation_(start), binding, initializer);
}
var assignment = new IdentifierExpression(name.location, token);
var initializer = this.parseInitializerOpt_(Expression.NORMAL);
return new AssignmentElement(this.getTreeLocation_(start), assignment, initializer);
},
parseAssignmentPattern_: function() {
return this.parsePattern_(false);
},
parseArrayAssignmentPattern_: function() {
return this.parseArrayPattern_(false);
},
parseAssignmentElement_: function() {
var start = this.getTreeStartLocation_();
var assignment = this.parseDestructuringAssignmentTarget_();
var initializer = this.parseInitializerOpt_(Expression.NORMAL);
return new AssignmentElement(this.getTreeLocation_(start), assignment, initializer);
},
parseDestructuringAssignmentTarget_: function() {
switch (this.peekType_()) {
case OPEN_SQUARE:
return this.parseArrayAssignmentPattern_();
case OPEN_CURLY:
return this.parseObjectAssignmentPattern_();
}
var expression = this.parseLeftHandSideExpression_();
return this.coverFormalsToParenExpression_(expression);
},
parseAssignmentRestElement_: function() {
var start = this.getTreeStartLocation_();
this.eat_(DOT_DOT_DOT);
var id = this.parseDestructuringAssignmentTarget_();
return new SpreadPatternElement(this.getTreeLocation_(start), id);
},
parseObjectAssignmentPattern_: function() {
return this.parseObjectPattern_(false);
},
parseAssignmentProperty_: function() {
return this.parsePatternProperty_(false);
},
parseTemplateLiteral_: function(operand) {
if (!parseOptions.templateLiterals)
return this.parseUnexpectedToken_('`');
var start = operand ? operand.location.start : this.getTreeStartLocation_();
var token = this.nextToken_();
var elements = [new TemplateLiteralPortion(token.location, token)];
if (token.type === NO_SUBSTITUTION_TEMPLATE) {
return new TemplateLiteralExpression(this.getTreeLocation_(start), operand, elements);
}
var expression = this.parseExpression();
elements.push(new TemplateSubstitution(expression.location, expression));
while (expression.type !== SYNTAX_ERROR_TREE) {
token = this.nextTemplateLiteralToken_();
if (token.type === ERROR || token.type === END_OF_FILE)
break;
elements.push(new TemplateLiteralPortion(token.location, token));
if (token.type === TEMPLATE_TAIL)
break;
expression = this.parseExpression();
elements.push(new TemplateSubstitution(expression.location, expression));
}
return new TemplateLiteralExpression(this.getTreeLocation_(start), operand, elements);
},
parseTypeAnnotationOpt_: function() {
if (parseOptions.types && this.eatOpt_(COLON)) {
return this.parseType_();
}
return null;
},
parseType_: function() {
var start = this.getTreeStartLocation_();
var elementType;
switch (this.peekType_()) {
case IDENTIFIER:
elementType = this.parseNamedOrPredefinedType_();
break;
case NEW:
elementType = this.parseConstructorType_();
break;
case OPEN_CURLY:
elementType = this.parseObjectType_();
break;
case OPEN_PAREN:
elementType = this.parseFunctionType_();
break;
case VOID:
var token = this.nextToken_();
return new PredefinedType(this.getTreeLocation_(start), token);
default:
return this.parseUnexpectedToken_(this.peekToken_());
}
return this.parseArrayTypeSuffix_(start, elementType);
},
parseArrayTypeSuffix_: function(start, elementType) {
return elementType;
},
parseConstructorType_: function() {
throw 'NYI';
},
parseObjectType_: function() {
throw 'NYI';
},
parseFunctionType_: function() {
throw 'NYI';
},
parseNamedOrPredefinedType_: function() {
var start = this.getTreeStartLocation_();
switch (this.peekToken_().value) {
case 'any':
case 'number':
case 'boolean':
case 'string':
var token = this.nextToken_();
return new PredefinedType(this.getTreeLocation_(start), token);
default:
return this.parseTypeName_();
}
},
parseTypeName_: function() {
var start = this.getTreeStartLocation_();
var typeName = new TypeName(this.getTreeLocation_(start), null, this.eatId_());
while (this.eatIf_(PERIOD)) {
var memberName = this.eatIdName_();
typeName = new TypeName(this.getTreeLocation_(start), typeName, memberName);
}
return typeName;
},
parseAnnotatedDeclarations_: function(allowModuleItem, allowScriptItem) {
this.pushAnnotations_();
var declaration = this.parseStatement_(this.peekType_(), allowModuleItem, allowScriptItem);
if (this.annotations_.length > 0)
return this.parseSyntaxError_('Unsupported annotated expression');
return declaration;
},
parseAnnotations_: function() {
var annotations = [];
while (this.eatIf_(AT)) {
annotations.push(this.parseAnnotation_());
}
return annotations;
},
pushAnnotations_: function() {
this.annotations_ = this.parseAnnotations_();
},
popAnnotations_: function() {
var annotations = this.annotations_;
this.annotations_ = [];
return annotations;
},
parseAnnotation_: function() {
var start = this.getTreeStartLocation_();
var expression = this.parseMemberExpressionNoNew_();
var args = null;
if (this.peek_(OPEN_PAREN))
args = this.parseArguments_();
return new Annotation(this.getTreeLocation_(start), expression, args);
},
eatPossibleImplicitSemiColon_: function() {
var token = this.peekTokenNoLineTerminator_();
if (!token)
return;
switch (token.type) {
case SEMI_COLON:
this.nextToken_();
return;
case END_OF_FILE:
case CLOSE_CURLY:
return;
}
this.reportError_('Semi-colon expected');
},
peekImplicitSemiColon_: function() {
switch (this.peekType_()) {
case SEMI_COLON:
case CLOSE_CURLY:
case END_OF_FILE:
return true;
}
var token = this.peekTokenNoLineTerminator_();
return token === null;
},
eatOpt_: function(expectedTokenType) {
if (this.peek_(expectedTokenType))
return this.nextToken_();
return null;
},
eatIdOpt_: function() {
return this.peek_(IDENTIFIER) ? this.eatId_() : null;
},
eatId_: function() {
var expected = arguments[0];
var token = this.nextToken_();
if (!token) {
if (expected)
this.reportError_(this.peekToken_(), ("expected '" + expected + "'"));
return null;
}
if (token.type === IDENTIFIER) {
if (expected && token.value !== expected)
this.reportExpectedError_(token, expected);
return token;
}
if (token.isStrictKeyword()) {
if (this.strictMode_) {
this.reportReservedIdentifier_(token);
} else {
return new IdentifierToken(token.location, token.type);
}
} else {
this.reportExpectedError_(token, expected || 'identifier');
}
return token;
},
eatIdName_: function() {
var t = this.nextToken_();
if (t.type != IDENTIFIER) {
if (!t.isKeyword()) {
this.reportExpectedError_(t, 'identifier');
return null;
}
return new IdentifierToken(t.location, t.type);
}
return t;
},
eat_: function(expectedTokenType) {
var token = this.nextToken_();
if (token.type != expectedTokenType) {
this.reportExpectedError_(token, expectedTokenType);
return null;
}
return token;
},
eatIf_: function(expectedTokenType) {
if (this.peek_(expectedTokenType)) {
this.nextToken_();
return true;
}
return false;
},
reportExpectedError_: function(token, expected) {
this.reportError_(token, ("Unexpected token " + token));
},
getTreeStartLocation_: function() {
return this.peekToken_().location.start;
},
getTreeEndLocation_: function() {
return this.scanner_.lastToken.location.end;
},
getTreeLocation_: function(start) {
return new SourceRange(start, this.getTreeEndLocation_());
},
handleComment: function(range) {},
nextToken_: function() {
return this.scanner_.nextToken();
},
nextRegularExpressionLiteralToken_: function() {
return this.scanner_.nextRegularExpressionLiteralToken();
},
nextTemplateLiteralToken_: function() {
return this.scanner_.nextTemplateLiteralToken();
},
isAtEnd: function() {
return this.scanner_.isAtEnd();
},
peek_: function(expectedType, opt_index) {
return this.peekToken_(opt_index).type === expectedType;
},
peekType_: function() {
return this.peekToken_().type;
},
peekToken_: function(opt_index) {
return this.scanner_.peekToken(opt_index);
},
peekTokenNoLineTerminator_: function() {
return this.scanner_.peekTokenNoLineTerminator();
},
reportError_: function() {
for (var args = [],
$__142 = 0; $__142 < arguments.length; $__142++)
args[$__142] = arguments[$__142];
if (args.length == 1) {
this.errorReporter_.reportError(this.scanner_.getPosition(), args[0]);
} else {
var location = args[0];
if (location instanceof Token) {
location = location.location;
}
this.errorReporter_.reportError(location.start, args[1]);
}
},
reportReservedIdentifier_: function(token) {
this.reportError_(token, (token.type + " is a reserved identifier"));
}
}, {});
return {get Parser() {
return Parser;
}};
});
System.register("traceur@0.0.52/src/util/SourcePosition", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/SourcePosition";
var SourcePosition = function SourcePosition(source, offset) {
this.source = source;
this.offset = offset;
this.line_ = -1;
this.column_ = -1;
};
($traceurRuntime.createClass)(SourcePosition, {
get line() {
if (this.line_ === -1)
this.line_ = this.source.lineNumberTable.getLine(this.offset);
return this.line_;
},
get column() {
if (this.column_ === -1)
this.column_ = this.source.lineNumberTable.getColumn(this.offset);
return this.column_;
},
toString: function() {
var name = this.source ? this.source.name : '';
return (name + ":" + (this.line + 1) + ":" + (this.column + 1));
}
}, {});
return {get SourcePosition() {
return SourcePosition;
}};
});
System.register("traceur@0.0.52/src/syntax/LineNumberTable", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/LineNumberTable";
var SourcePosition = System.get("traceur@0.0.52/src/util/SourcePosition").SourcePosition;
var SourceRange = System.get("traceur@0.0.52/src/util/SourceRange").SourceRange;
var isLineTerminator = System.get("traceur@0.0.52/src/syntax/Scanner").isLineTerminator;
var MAX_INT_REPRESENTATION = 9007199254740992;
function computeLineStartOffsets(source) {
var lineStartOffsets = [0];
var k = 1;
for (var index = 0; index < source.length; index++) {
var code = source.charCodeAt(index);
if (isLineTerminator(code)) {
if (code === 13 && source.charCodeAt(index + 1) === 10) {
index++;
}
lineStartOffsets[k++] = index + 1;
}
}
lineStartOffsets[k++] = MAX_INT_REPRESENTATION;
return lineStartOffsets;
}
var LineNumberTable = function LineNumberTable(sourceFile) {
this.sourceFile_ = sourceFile;
this.lineStartOffsets_ = null;
this.lastLine_ = 0;
this.lastOffset_ = -1;
};
($traceurRuntime.createClass)(LineNumberTable, {
ensureLineStartOffsets_: function() {
if (!this.lineStartOffsets_) {
this.lineStartOffsets_ = computeLineStartOffsets(this.sourceFile_.contents);
}
},
getSourcePosition: function(offset) {
return new SourcePosition(this.sourceFile_, offset);
},
getLine: function(offset) {
if (offset === this.lastOffset_)
return this.lastLine_;
this.ensureLineStartOffsets_();
if (offset < 0)
return 0;
var line;
if (offset < this.lastOffset_) {
for (var i = this.lastLine_; i >= 0; i--) {
if (this.lineStartOffsets_[i] <= offset) {
line = i;
break;
}
}
} else {
for (var i = this.lastLine_; true; i++) {
if (this.lineStartOffsets_[i] > offset) {
line = i - 1;
break;
}
}
}
this.lastLine_ = line;
this.lastOffset_ = offset;
return line;
},
offsetOfLine: function(line) {
this.ensureLineStartOffsets_();
return this.lineStartOffsets_[line];
},
getColumn: function(offset) {
var line = this.getLine(offset);
return offset - this.lineStartOffsets_[line];
},
getSourceRange: function(startOffset, endOffset) {
return new SourceRange(this.getSourcePosition(startOffset), this.getSourcePosition(endOffset));
}
}, {});
return {get LineNumberTable() {
return LineNumberTable;
}};
});
System.register("traceur@0.0.52/src/syntax/SourceFile", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/SourceFile";
var LineNumberTable = System.get("traceur@0.0.52/src/syntax/LineNumberTable").LineNumberTable;
var SourceFile = function SourceFile(name, contents) {
this.name = name;
this.contents = contents;
this.lineNumberTable = new LineNumberTable(this);
};
($traceurRuntime.createClass)(SourceFile, {}, {});
return {get SourceFile() {
return SourceFile;
}};
});
System.register("traceur@0.0.52/src/util/MutedErrorReporter", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/MutedErrorReporter";
var ErrorReporter = System.get("traceur@0.0.52/src/util/ErrorReporter").ErrorReporter;
var MutedErrorReporter = function MutedErrorReporter() {
$traceurRuntime.defaultSuperCall(this, $MutedErrorReporter.prototype, arguments);
};
var $MutedErrorReporter = MutedErrorReporter;
($traceurRuntime.createClass)(MutedErrorReporter, {reportMessageInternal: function(location, format, args) {}}, {}, ErrorReporter);
return {get MutedErrorReporter() {
return MutedErrorReporter;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ParseTreeTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ParseTreeTransformer";
var $__152 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
Annotation = $__152.Annotation,
AnonBlock = $__152.AnonBlock,
ArgumentList = $__152.ArgumentList,
ArrayComprehension = $__152.ArrayComprehension,
ArrayLiteralExpression = $__152.ArrayLiteralExpression,
ArrayPattern = $__152.ArrayPattern,
ArrowFunctionExpression = $__152.ArrowFunctionExpression,
AssignmentElement = $__152.AssignmentElement,
AwaitExpression = $__152.AwaitExpression,
BinaryExpression = $__152.BinaryExpression,
BindingElement = $__152.BindingElement,
BindingIdentifier = $__152.BindingIdentifier,
Block = $__152.Block,
BreakStatement = $__152.BreakStatement,
CallExpression = $__152.CallExpression,
CaseClause = $__152.CaseClause,
Catch = $__152.Catch,
ClassDeclaration = $__152.ClassDeclaration,
ClassExpression = $__152.ClassExpression,
CommaExpression = $__152.CommaExpression,
ComprehensionFor = $__152.ComprehensionFor,
ComprehensionIf = $__152.ComprehensionIf,
ComputedPropertyName = $__152.ComputedPropertyName,
ConditionalExpression = $__152.ConditionalExpression,
ContinueStatement = $__152.ContinueStatement,
CoverFormals = $__152.CoverFormals,
CoverInitializedName = $__152.CoverInitializedName,
DebuggerStatement = $__152.DebuggerStatement,
DefaultClause = $__152.DefaultClause,
DoWhileStatement = $__152.DoWhileStatement,
EmptyStatement = $__152.EmptyStatement,
ExportDeclaration = $__152.ExportDeclaration,
ExportDefault = $__152.ExportDefault,
ExportSpecifier = $__152.ExportSpecifier,
ExportSpecifierSet = $__152.ExportSpecifierSet,
ExportStar = $__152.ExportStar,
ExpressionStatement = $__152.ExpressionStatement,
Finally = $__152.Finally,
ForInStatement = $__152.ForInStatement,
ForOfStatement = $__152.ForOfStatement,
ForStatement = $__152.ForStatement,
FormalParameter = $__152.FormalParameter,
FormalParameterList = $__152.FormalParameterList,
FunctionBody = $__152.FunctionBody,
FunctionDeclaration = $__152.FunctionDeclaration,
FunctionExpression = $__152.FunctionExpression,
GeneratorComprehension = $__152.GeneratorComprehension,
GetAccessor = $__152.GetAccessor,
IdentifierExpression = $__152.IdentifierExpression,
IfStatement = $__152.IfStatement,
ImportedBinding = $__152.ImportedBinding,
ImportDeclaration = $__152.ImportDeclaration,
ImportSpecifier = $__152.ImportSpecifier,
ImportSpecifierSet = $__152.ImportSpecifierSet,
LabelledStatement = $__152.LabelledStatement,
LiteralExpression = $__152.LiteralExpression,
LiteralPropertyName = $__152.LiteralPropertyName,
MemberExpression = $__152.MemberExpression,
MemberLookupExpression = $__152.MemberLookupExpression,
Module = $__152.Module,
ModuleDeclaration = $__152.ModuleDeclaration,
ModuleSpecifier = $__152.ModuleSpecifier,
NamedExport = $__152.NamedExport,
NewExpression = $__152.NewExpression,
ObjectLiteralExpression = $__152.ObjectLiteralExpression,
ObjectPattern = $__152.ObjectPattern,
ObjectPatternField = $__152.ObjectPatternField,
ParenExpression = $__152.ParenExpression,
PostfixExpression = $__152.PostfixExpression,
PredefinedType = $__152.PredefinedType,
Script = $__152.Script,
PropertyMethodAssignment = $__152.PropertyMethodAssignment,
PropertyNameAssignment = $__152.PropertyNameAssignment,
PropertyNameShorthand = $__152.PropertyNameShorthand,
RestParameter = $__152.RestParameter,
ReturnStatement = $__152.ReturnStatement,
SetAccessor = $__152.SetAccessor,
SpreadExpression = $__152.SpreadExpression,
SpreadPatternElement = $__152.SpreadPatternElement,
SuperExpression = $__152.SuperExpression,
SwitchStatement = $__152.SwitchStatement,
SyntaxErrorTree = $__152.SyntaxErrorTree,
TemplateLiteralExpression = $__152.TemplateLiteralExpression,
TemplateLiteralPortion = $__152.TemplateLiteralPortion,
TemplateSubstitution = $__152.TemplateSubstitution,
ThisExpression = $__152.ThisExpression,
ThrowStatement = $__152.ThrowStatement,
TryStatement = $__152.TryStatement,
TypeName = $__152.TypeName,
UnaryExpression = $__152.UnaryExpression,
VariableDeclaration = $__152.VariableDeclaration,
VariableDeclarationList = $__152.VariableDeclarationList,
VariableStatement = $__152.VariableStatement,
WhileStatement = $__152.WhileStatement,
WithStatement = $__152.WithStatement,
YieldExpression = $__152.YieldExpression;
var ParseTreeTransformer = function ParseTreeTransformer() {};
($traceurRuntime.createClass)(ParseTreeTransformer, {
transformAny: function(tree) {
return tree && tree.transform(this);
},
transformList: function(list) {
var $__154;
var builder = null;
for (var index = 0; index < list.length; index++) {
var element = list[index];
var transformed = this.transformAny(element);
if (builder != null || element != transformed) {
if (builder == null) {
builder = list.slice(0, index);
}
if (transformed instanceof AnonBlock)
($__154 = builder).push.apply($__154, $traceurRuntime.spread(transformed.statements));
else
builder.push(transformed);
}
}
return builder || list;
},
transformStateMachine: function(tree) {
throw Error('State machines should not live outside of the GeneratorTransformer.');
},
transformAnnotation: function(tree) {
var name = this.transformAny(tree.name);
var args = this.transformAny(tree.args);
if (name === tree.name && args === tree.args) {
return tree;
}
return new Annotation(tree.location, name, args);
},
transformAnonBlock: function(tree) {
var statements = this.transformList(tree.statements);
if (statements === tree.statements) {
return tree;
}
return new AnonBlock(tree.location, statements);
},
transformArgumentList: function(tree) {
var args = this.transformList(tree.args);
if (args === tree.args) {
return tree;
}
return new ArgumentList(tree.location, args);
},
transformArrayComprehension: function(tree) {
var comprehensionList = this.transformList(tree.comprehensionList);
var expression = this.transformAny(tree.expression);
if (comprehensionList === tree.comprehensionList && expression === tree.expression) {
return tree;
}
return new ArrayComprehension(tree.location, comprehensionList, expression);
},
transformArrayLiteralExpression: function(tree) {
var elements = this.transformList(tree.elements);
if (elements === tree.elements) {
return tree;
}
return new ArrayLiteralExpression(tree.location, elements);
},
transformArrayPattern: function(tree) {
var elements = this.transformList(tree.elements);
if (elements === tree.elements) {
return tree;
}
return new ArrayPattern(tree.location, elements);
},
transformArrowFunctionExpression: function(tree) {
var parameterList = this.transformAny(tree.parameterList);
var body = this.transformAny(tree.body);
if (parameterList === tree.parameterList && body === tree.body) {
return tree;
}
return new ArrowFunctionExpression(tree.location, tree.functionKind, parameterList, body);
},
transformAssignmentElement: function(tree) {
var assignment = this.transformAny(tree.assignment);
var initializer = this.transformAny(tree.initializer);
if (assignment === tree.assignment && initializer === tree.initializer) {
return tree;
}
return new AssignmentElement(tree.location, assignment, initializer);
},
transformAwaitExpression: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new AwaitExpression(tree.location, expression);
},
transformBinaryExpression: function(tree) {
var left = this.transformAny(tree.left);
var right = this.transformAny(tree.right);
if (left === tree.left && right === tree.right) {
return tree;
}
return new BinaryExpression(tree.location, left, tree.operator, right);
},
transformBindingElement: function(tree) {
var binding = this.transformAny(tree.binding);
var initializer = this.transformAny(tree.initializer);
if (binding === tree.binding && initializer === tree.initializer) {
return tree;
}
return new BindingElement(tree.location, binding, initializer);
},
transformBindingIdentifier: function(tree) {
return tree;
},
transformBlock: function(tree) {
var statements = this.transformList(tree.statements);
if (statements === tree.statements) {
return tree;
}
return new Block(tree.location, statements);
},
transformBreakStatement: function(tree) {
return tree;
},
transformCallExpression: function(tree) {
var operand = this.transformAny(tree.operand);
var args = this.transformAny(tree.args);
if (operand === tree.operand && args === tree.args) {
return tree;
}
return new CallExpression(tree.location, operand, args);
},
transformCaseClause: function(tree) {
var expression = this.transformAny(tree.expression);
var statements = this.transformList(tree.statements);
if (expression === tree.expression && statements === tree.statements) {
return tree;
}
return new CaseClause(tree.location, expression, statements);
},
transformCatch: function(tree) {
var binding = this.transformAny(tree.binding);
var catchBody = this.transformAny(tree.catchBody);
if (binding === tree.binding && catchBody === tree.catchBody) {
return tree;
}
return new Catch(tree.location, binding, catchBody);
},
transformClassDeclaration: function(tree) {
var name = this.transformAny(tree.name);
var superClass = this.transformAny(tree.superClass);
var elements = this.transformList(tree.elements);
var annotations = this.transformList(tree.annotations);
if (name === tree.name && superClass === tree.superClass && elements === tree.elements && annotations === tree.annotations) {
return tree;
}
return new ClassDeclaration(tree.location, name, superClass, elements, annotations);
},
transformClassExpression: function(tree) {
var name = this.transformAny(tree.name);
var superClass = this.transformAny(tree.superClass);
var elements = this.transformList(tree.elements);
var annotations = this.transformList(tree.annotations);
if (name === tree.name && superClass === tree.superClass && elements === tree.elements && annotations === tree.annotations) {
return tree;
}
return new ClassExpression(tree.location, name, superClass, elements, annotations);
},
transformCommaExpression: function(tree) {
var expressions = this.transformList(tree.expressions);
if (expressions === tree.expressions) {
return tree;
}
return new CommaExpression(tree.location, expressions);
},
transformComprehensionFor: function(tree) {
var left = this.transformAny(tree.left);
var iterator = this.transformAny(tree.iterator);
if (left === tree.left && iterator === tree.iterator) {
return tree;
}
return new ComprehensionFor(tree.location, left, iterator);
},
transformComprehensionIf: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new ComprehensionIf(tree.location, expression);
},
transformComputedPropertyName: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new ComputedPropertyName(tree.location, expression);
},
transformConditionalExpression: function(tree) {
var condition = this.transformAny(tree.condition);
var left = this.transformAny(tree.left);
var right = this.transformAny(tree.right);
if (condition === tree.condition && left === tree.left && right === tree.right) {
return tree;
}
return new ConditionalExpression(tree.location, condition, left, right);
},
transformContinueStatement: function(tree) {
return tree;
},
transformCoverFormals: function(tree) {
var expressions = this.transformList(tree.expressions);
if (expressions === tree.expressions) {
return tree;
}
return new CoverFormals(tree.location, expressions);
},
transformCoverInitializedName: function(tree) {
var initializer = this.transformAny(tree.initializer);
if (initializer === tree.initializer) {
return tree;
}
return new CoverInitializedName(tree.location, tree.name, tree.equalToken, initializer);
},
transformDebuggerStatement: function(tree) {
return tree;
},
transformDefaultClause: function(tree) {
var statements = this.transformList(tree.statements);
if (statements === tree.statements) {
return tree;
}
return new DefaultClause(tree.location, statements);
},
transformDoWhileStatement: function(tree) {
var body = this.transformAny(tree.body);
var condition = this.transformAny(tree.condition);
if (body === tree.body && condition === tree.condition) {
return tree;
}
return new DoWhileStatement(tree.location, body, condition);
},
transformEmptyStatement: function(tree) {
return tree;
},
transformExportDeclaration: function(tree) {
var declaration = this.transformAny(tree.declaration);
var annotations = this.transformList(tree.annotations);
if (declaration === tree.declaration && annotations === tree.annotations) {
return tree;
}
return new ExportDeclaration(tree.location, declaration, annotations);
},
transformExportDefault: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new ExportDefault(tree.location, expression);
},
transformExportSpecifier: function(tree) {
return tree;
},
transformExportSpecifierSet: function(tree) {
var specifiers = this.transformList(tree.specifiers);
if (specifiers === tree.specifiers) {
return tree;
}
return new ExportSpecifierSet(tree.location, specifiers);
},
transformExportStar: function(tree) {
return tree;
},
transformExpressionStatement: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new ExpressionStatement(tree.location, expression);
},
transformFinally: function(tree) {
var block = this.transformAny(tree.block);
if (block === tree.block) {
return tree;
}
return new Finally(tree.location, block);
},
transformForInStatement: function(tree) {
var initializer = this.transformAny(tree.initializer);
var collection = this.transformAny(tree.collection);
var body = this.transformAny(tree.body);
if (initializer === tree.initializer && collection === tree.collection && body === tree.body) {
return tree;
}
return new ForInStatement(tree.location, initializer, collection, body);
},
transformForOfStatement: function(tree) {
var initializer = this.transformAny(tree.initializer);
var collection = this.transformAny(tree.collection);
var body = this.transformAny(tree.body);
if (initializer === tree.initializer && collection === tree.collection && body === tree.body) {
return tree;
}
return new ForOfStatement(tree.location, initializer, collection, body);
},
transformForStatement: function(tree) {
var initializer = this.transformAny(tree.initializer);
var condition = this.transformAny(tree.condition);
var increment = this.transformAny(tree.increment);
var body = this.transformAny(tree.body);
if (initializer === tree.initializer && condition === tree.condition && increment === tree.increment && body === tree.body) {
return tree;
}
return new ForStatement(tree.location, initializer, condition, increment, body);
},
transformFormalParameter: function(tree) {
var parameter = this.transformAny(tree.parameter);
var typeAnnotation = this.transformAny(tree.typeAnnotation);
var annotations = this.transformList(tree.annotations);
if (parameter === tree.parameter && typeAnnotation === tree.typeAnnotation && annotations === tree.annotations) {
return tree;
}
return new FormalParameter(tree.location, parameter, typeAnnotation, annotations);
},
transformFormalParameterList: function(tree) {
var parameters = this.transformList(tree.parameters);
if (parameters === tree.parameters) {
return tree;
}
return new FormalParameterList(tree.location, parameters);
},
transformFunctionBody: function(tree) {
var statements = this.transformList(tree.statements);
if (statements === tree.statements) {
return tree;
}
return new FunctionBody(tree.location, statements);
},
transformFunctionDeclaration: function(tree) {
var name = this.transformAny(tree.name);
var parameterList = this.transformAny(tree.parameterList);
var typeAnnotation = this.transformAny(tree.typeAnnotation);
var annotations = this.transformList(tree.annotations);
var body = this.transformAny(tree.body);
if (name === tree.name && parameterList === tree.parameterList && typeAnnotation === tree.typeAnnotation && annotations === tree.annotations && body === tree.body) {
return tree;
}
return new FunctionDeclaration(tree.location, name, tree.functionKind, parameterList, typeAnnotation, annotations, body);
},
transformFunctionExpression: function(tree) {
var name = this.transformAny(tree.name);
var parameterList = this.transformAny(tree.parameterList);
var typeAnnotation = this.transformAny(tree.typeAnnotation);
var annotations = this.transformList(tree.annotations);
var body = this.transformAny(tree.body);
if (name === tree.name && parameterList === tree.parameterList && typeAnnotation === tree.typeAnnotation && annotations === tree.annotations && body === tree.body) {
return tree;
}
return new FunctionExpression(tree.location, name, tree.functionKind, parameterList, typeAnnotation, annotations, body);
},
transformGeneratorComprehension: function(tree) {
var comprehensionList = this.transformList(tree.comprehensionList);
var expression = this.transformAny(tree.expression);
if (comprehensionList === tree.comprehensionList && expression === tree.expression) {
return tree;
}
return new GeneratorComprehension(tree.location, comprehensionList, expression);
},
transformGetAccessor: function(tree) {
var name = this.transformAny(tree.name);
var typeAnnotation = this.transformAny(tree.typeAnnotation);
var annotations = this.transformList(tree.annotations);
var body = this.transformAny(tree.body);
if (name === tree.name && typeAnnotation === tree.typeAnnotation && annotations === tree.annotations && body === tree.body) {
return tree;
}
return new GetAccessor(tree.location, tree.isStatic, name, typeAnnotation, annotations, body);
},
transformIdentifierExpression: function(tree) {
return tree;
},
transformIfStatement: function(tree) {
var condition = this.transformAny(tree.condition);
var ifClause = this.transformAny(tree.ifClause);
var elseClause = this.transformAny(tree.elseClause);
if (condition === tree.condition && ifClause === tree.ifClause && elseClause === tree.elseClause) {
return tree;
}
return new IfStatement(tree.location, condition, ifClause, elseClause);
},
transformImportedBinding: function(tree) {
var binding = this.transformAny(tree.binding);
if (binding === tree.binding) {
return tree;
}
return new ImportedBinding(tree.location, binding);
},
transformImportDeclaration: function(tree) {
var importClause = this.transformAny(tree.importClause);
var moduleSpecifier = this.transformAny(tree.moduleSpecifier);
if (importClause === tree.importClause && moduleSpecifier === tree.moduleSpecifier) {
return tree;
}
return new ImportDeclaration(tree.location, importClause, moduleSpecifier);
},
transformImportSpecifier: function(tree) {
return tree;
},
transformImportSpecifierSet: function(tree) {
var specifiers = this.transformList(tree.specifiers);
if (specifiers === tree.specifiers) {
return tree;
}
return new ImportSpecifierSet(tree.location, specifiers);
},
transformLabelledStatement: function(tree) {
var statement = this.transformAny(tree.statement);
if (statement === tree.statement) {
return tree;
}
return new LabelledStatement(tree.location, tree.name, statement);
},
transformLiteralExpression: function(tree) {
return tree;
},
transformLiteralPropertyName: function(tree) {
return tree;
},
transformMemberExpression: function(tree) {
var operand = this.transformAny(tree.operand);
if (operand === tree.operand) {
return tree;
}
return new MemberExpression(tree.location, operand, tree.memberName);
},
transformMemberLookupExpression: function(tree) {
var operand = this.transformAny(tree.operand);
var memberExpression = this.transformAny(tree.memberExpression);
if (operand === tree.operand && memberExpression === tree.memberExpression) {
return tree;
}
return new MemberLookupExpression(tree.location, operand, memberExpression);
},
transformModule: function(tree) {
var scriptItemList = this.transformList(tree.scriptItemList);
if (scriptItemList === tree.scriptItemList) {
return tree;
}
return new Module(tree.location, scriptItemList, tree.moduleName);
},
transformModuleDeclaration: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new ModuleDeclaration(tree.location, tree.identifier, expression);
},
transformModuleSpecifier: function(tree) {
return tree;
},
transformNamedExport: function(tree) {
var moduleSpecifier = this.transformAny(tree.moduleSpecifier);
var specifierSet = this.transformAny(tree.specifierSet);
if (moduleSpecifier === tree.moduleSpecifier && specifierSet === tree.specifierSet) {
return tree;
}
return new NamedExport(tree.location, moduleSpecifier, specifierSet);
},
transformNewExpression: function(tree) {
var operand = this.transformAny(tree.operand);
var args = this.transformAny(tree.args);
if (operand === tree.operand && args === tree.args) {
return tree;
}
return new NewExpression(tree.location, operand, args);
},
transformObjectLiteralExpression: function(tree) {
var propertyNameAndValues = this.transformList(tree.propertyNameAndValues);
if (propertyNameAndValues === tree.propertyNameAndValues) {
return tree;
}
return new ObjectLiteralExpression(tree.location, propertyNameAndValues);
},
transformObjectPattern: function(tree) {
var fields = this.transformList(tree.fields);
if (fields === tree.fields) {
return tree;
}
return new ObjectPattern(tree.location, fields);
},
transformObjectPatternField: function(tree) {
var name = this.transformAny(tree.name);
var element = this.transformAny(tree.element);
if (name === tree.name && element === tree.element) {
return tree;
}
return new ObjectPatternField(tree.location, name, element);
},
transformParenExpression: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new ParenExpression(tree.location, expression);
},
transformPostfixExpression: function(tree) {
var operand = this.transformAny(tree.operand);
if (operand === tree.operand) {
return tree;
}
return new PostfixExpression(tree.location, operand, tree.operator);
},
transformPredefinedType: function(tree) {
return tree;
},
transformScript: function(tree) {
var scriptItemList = this.transformList(tree.scriptItemList);
if (scriptItemList === tree.scriptItemList) {
return tree;
}
return new Script(tree.location, scriptItemList, tree.moduleName);
},
transformPropertyMethodAssignment: function(tree) {
var name = this.transformAny(tree.name);
var parameterList = this.transformAny(tree.parameterList);
var typeAnnotation = this.transformAny(tree.typeAnnotation);
var annotations = this.transformList(tree.annotations);
var body = this.transformAny(tree.body);
if (name === tree.name && parameterList === tree.parameterList && typeAnnotation === tree.typeAnnotation && annotations === tree.annotations && body === tree.body) {
return tree;
}
return new PropertyMethodAssignment(tree.location, tree.isStatic, tree.functionKind, name, parameterList, typeAnnotation, annotations, body);
},
transformPropertyNameAssignment: function(tree) {
var name = this.transformAny(tree.name);
var value = this.transformAny(tree.value);
if (name === tree.name && value === tree.value) {
return tree;
}
return new PropertyNameAssignment(tree.location, name, value);
},
transformPropertyNameShorthand: function(tree) {
return tree;
},
transformRestParameter: function(tree) {
var identifier = this.transformAny(tree.identifier);
if (identifier === tree.identifier) {
return tree;
}
return new RestParameter(tree.location, identifier);
},
transformReturnStatement: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new ReturnStatement(tree.location, expression);
},
transformSetAccessor: function(tree) {
var name = this.transformAny(tree.name);
var parameterList = this.transformAny(tree.parameterList);
var annotations = this.transformList(tree.annotations);
var body = this.transformAny(tree.body);
if (name === tree.name && parameterList === tree.parameterList && annotations === tree.annotations && body === tree.body) {
return tree;
}
return new SetAccessor(tree.location, tree.isStatic, name, parameterList, annotations, body);
},
transformSpreadExpression: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new SpreadExpression(tree.location, expression);
},
transformSpreadPatternElement: function(tree) {
var lvalue = this.transformAny(tree.lvalue);
if (lvalue === tree.lvalue) {
return tree;
}
return new SpreadPatternElement(tree.location, lvalue);
},
transformSuperExpression: function(tree) {
return tree;
},
transformSwitchStatement: function(tree) {
var expression = this.transformAny(tree.expression);
var caseClauses = this.transformList(tree.caseClauses);
if (expression === tree.expression && caseClauses === tree.caseClauses) {
return tree;
}
return new SwitchStatement(tree.location, expression, caseClauses);
},
transformSyntaxErrorTree: function(tree) {
return tree;
},
transformTemplateLiteralExpression: function(tree) {
var operand = this.transformAny(tree.operand);
var elements = this.transformList(tree.elements);
if (operand === tree.operand && elements === tree.elements) {
return tree;
}
return new TemplateLiteralExpression(tree.location, operand, elements);
},
transformTemplateLiteralPortion: function(tree) {
return tree;
},
transformTemplateSubstitution: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new TemplateSubstitution(tree.location, expression);
},
transformThisExpression: function(tree) {
return tree;
},
transformThrowStatement: function(tree) {
var value = this.transformAny(tree.value);
if (value === tree.value) {
return tree;
}
return new ThrowStatement(tree.location, value);
},
transformTryStatement: function(tree) {
var body = this.transformAny(tree.body);
var catchBlock = this.transformAny(tree.catchBlock);
var finallyBlock = this.transformAny(tree.finallyBlock);
if (body === tree.body && catchBlock === tree.catchBlock && finallyBlock === tree.finallyBlock) {
return tree;
}
return new TryStatement(tree.location, body, catchBlock, finallyBlock);
},
transformTypeName: function(tree) {
var moduleName = this.transformAny(tree.moduleName);
if (moduleName === tree.moduleName) {
return tree;
}
return new TypeName(tree.location, moduleName, tree.name);
},
transformUnaryExpression: function(tree) {
var operand = this.transformAny(tree.operand);
if (operand === tree.operand) {
return tree;
}
return new UnaryExpression(tree.location, tree.operator, operand);
},
transformVariableDeclaration: function(tree) {
var lvalue = this.transformAny(tree.lvalue);
var typeAnnotation = this.transformAny(tree.typeAnnotation);
var initializer = this.transformAny(tree.initializer);
if (lvalue === tree.lvalue && typeAnnotation === tree.typeAnnotation && initializer === tree.initializer) {
return tree;
}
return new VariableDeclaration(tree.location, lvalue, typeAnnotation, initializer);
},
transformVariableDeclarationList: function(tree) {
var declarations = this.transformList(tree.declarations);
if (declarations === tree.declarations) {
return tree;
}
return new VariableDeclarationList(tree.location, tree.declarationType, declarations);
},
transformVariableStatement: function(tree) {
var declarations = this.transformAny(tree.declarations);
if (declarations === tree.declarations) {
return tree;
}
return new VariableStatement(tree.location, declarations);
},
transformWhileStatement: function(tree) {
var condition = this.transformAny(tree.condition);
var body = this.transformAny(tree.body);
if (condition === tree.condition && body === tree.body) {
return tree;
}
return new WhileStatement(tree.location, condition, body);
},
transformWithStatement: function(tree) {
var expression = this.transformAny(tree.expression);
var body = this.transformAny(tree.body);
if (expression === tree.expression && body === tree.body) {
return tree;
}
return new WithStatement(tree.location, expression, body);
},
transformYieldExpression: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression) {
return tree;
}
return new YieldExpression(tree.location, expression, tree.isYieldFor);
}
}, {});
return {get ParseTreeTransformer() {
return ParseTreeTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/PlaceholderParser", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/PlaceholderParser";
var $__155 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
ARGUMENT_LIST = $__155.ARGUMENT_LIST,
BLOCK = $__155.BLOCK,
EXPRESSION_STATEMENT = $__155.EXPRESSION_STATEMENT,
IDENTIFIER_EXPRESSION = $__155.IDENTIFIER_EXPRESSION;
var IdentifierToken = System.get("traceur@0.0.52/src/syntax/IdentifierToken").IdentifierToken;
var LiteralToken = System.get("traceur@0.0.52/src/syntax/LiteralToken").LiteralToken;
var Map = System.get("traceur@0.0.52/src/runtime/polyfills/Map").Map;
var MutedErrorReporter = System.get("traceur@0.0.52/src/util/MutedErrorReporter").MutedErrorReporter;
var ParseTree = System.get("traceur@0.0.52/src/syntax/trees/ParseTree").ParseTree;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var Parser = System.get("traceur@0.0.52/src/syntax/Parser").Parser;
var $__163 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
LiteralExpression = $__163.LiteralExpression,
LiteralPropertyName = $__163.LiteralPropertyName;
var SourceFile = System.get("traceur@0.0.52/src/syntax/SourceFile").SourceFile;
var IDENTIFIER = System.get("traceur@0.0.52/src/syntax/TokenType").IDENTIFIER;
var $__166 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArrayLiteralExpression = $__166.createArrayLiteralExpression,
createBindingIdentifier = $__166.createBindingIdentifier,
createBlock = $__166.createBlock,
createBooleanLiteral = $__166.createBooleanLiteral,
createCommaExpression = $__166.createCommaExpression,
createExpressionStatement = $__166.createExpressionStatement,
createFunctionBody = $__166.createFunctionBody,
createIdentifierExpression = $__166.createIdentifierExpression,
createIdentifierToken = $__166.createIdentifierToken,
createMemberExpression = $__166.createMemberExpression,
createNullLiteral = $__166.createNullLiteral,
createNumberLiteral = $__166.createNumberLiteral,
createParenExpression = $__166.createParenExpression,
createStringLiteral = $__166.createStringLiteral,
createVoid0 = $__166.createVoid0;
var NOT_FOUND = {};
var PREFIX = '$__placeholder__';
var cache = new Map();
function parseExpression(sourceLiterals) {
for (var values = [],
$__168 = 1; $__168 < arguments.length; $__168++)
values[$__168 - 1] = arguments[$__168];
return parse(sourceLiterals, values, (function() {
return new PlaceholderParser().parseExpression(sourceLiterals);
}));
}
function parseStatement(sourceLiterals) {
for (var values = [],
$__169 = 1; $__169 < arguments.length; $__169++)
values[$__169 - 1] = arguments[$__169];
return parse(sourceLiterals, values, (function() {
return new PlaceholderParser().parseStatement(sourceLiterals);
}));
}
function parseStatements(sourceLiterals) {
for (var values = [],
$__170 = 1; $__170 < arguments.length; $__170++)
values[$__170 - 1] = arguments[$__170];
return parse(sourceLiterals, values, (function() {
return new PlaceholderParser().parseStatements(sourceLiterals);
}));
}
function parsePropertyDefinition(sourceLiterals) {
for (var values = [],
$__171 = 1; $__171 < arguments.length; $__171++)
values[$__171 - 1] = arguments[$__171];
return parse(sourceLiterals, values, (function() {
return new PlaceholderParser().parsePropertyDefinition(sourceLiterals);
}));
}
function parse(sourceLiterals, values, doParse) {
var tree = cache.get(sourceLiterals);
if (!tree) {
tree = doParse();
cache.set(sourceLiterals, tree);
}
if (!values.length)
return tree;
if (tree instanceof ParseTree)
return new PlaceholderTransformer(values).transformAny(tree);
return new PlaceholderTransformer(values).transformList(tree);
}
var counter = 0;
var PlaceholderParser = function PlaceholderParser() {};
($traceurRuntime.createClass)(PlaceholderParser, {
parseExpression: function(sourceLiterals) {
return this.parse_(sourceLiterals, (function(p) {
return p.parseExpression();
}));
},
parseStatement: function(sourceLiterals) {
return this.parse_(sourceLiterals, (function(p) {
return p.parseStatement();
}));
},
parseStatements: function(sourceLiterals) {
return this.parse_(sourceLiterals, (function(p) {
return p.parseStatements();
}));
},
parsePropertyDefinition: function(sourceLiterals) {
return this.parse_(sourceLiterals, (function(p) {
return p.parsePropertyDefinition();
}));
},
parse_: function(sourceLiterals, doParse) {
var source = sourceLiterals[0];
for (var i = 1; i < sourceLiterals.length; i++) {
source += PREFIX + (i - 1) + sourceLiterals[i];
}
var file = new SourceFile('@traceur/generated/TemplateParser/' + counter++, source);
var errorReporter = new MutedErrorReporter();
var parser = new Parser(file, errorReporter);
var tree = doParse(parser);
if (errorReporter.hadError() || !tree || !parser.isAtEnd())
throw new Error(("Internal error trying to parse:\n\n" + source));
return tree;
}
}, {});
function convertValueToExpression(value) {
if (value instanceof ParseTree)
return value;
if (value instanceof IdentifierToken)
return createIdentifierExpression(value);
if (value instanceof LiteralToken)
return new LiteralExpression(value.location, value);
if (Array.isArray(value)) {
if (value[0] instanceof ParseTree) {
if (value.length === 1)
return value[0];
if (value[0].isStatement())
return createBlock(value);
else
return createParenExpression(createCommaExpression(value));
}
return createArrayLiteralExpression(value.map(convertValueToExpression));
}
if (value === null)
return createNullLiteral();
if (value === undefined)
return createVoid0();
switch (typeof value) {
case 'string':
return createStringLiteral(value);
case 'boolean':
return createBooleanLiteral(value);
case 'number':
return createNumberLiteral(value);
}
throw new Error('Not implemented');
}
function convertValueToIdentifierToken(value) {
if (value instanceof IdentifierToken)
return value;
return createIdentifierToken(value);
}
var PlaceholderTransformer = function PlaceholderTransformer(values) {
$traceurRuntime.superCall(this, $PlaceholderTransformer.prototype, "constructor", []);
this.values = values;
};
var $PlaceholderTransformer = PlaceholderTransformer;
($traceurRuntime.createClass)(PlaceholderTransformer, {
getValueAt: function(index) {
return this.values[index];
},
getValue_: function(str) {
if (str.indexOf(PREFIX) !== 0)
return NOT_FOUND;
return this.getValueAt(Number(str.slice(PREFIX.length)));
},
transformIdentifierExpression: function(tree) {
var value = this.getValue_(tree.identifierToken.value);
if (value === NOT_FOUND)
return tree;
return convertValueToExpression(value);
},
transformBindingIdentifier: function(tree) {
var value = this.getValue_(tree.identifierToken.value);
if (value === NOT_FOUND)
return tree;
return createBindingIdentifier(value);
},
transformExpressionStatement: function(tree) {
if (tree.expression.type === IDENTIFIER_EXPRESSION) {
var transformedExpression = this.transformIdentifierExpression(tree.expression);
if (transformedExpression === tree.expression)
return tree;
if (transformedExpression.isStatement())
return transformedExpression;
return createExpressionStatement(transformedExpression);
}
return $traceurRuntime.superCall(this, $PlaceholderTransformer.prototype, "transformExpressionStatement", [tree]);
},
transformBlock: function(tree) {
if (tree.statements.length === 1 && tree.statements[0].type === EXPRESSION_STATEMENT) {
var transformedStatement = this.transformExpressionStatement(tree.statements[0]);
if (transformedStatement === tree.statements[0])
return tree;
if (transformedStatement.type === BLOCK)
return transformedStatement;
}
return $traceurRuntime.superCall(this, $PlaceholderTransformer.prototype, "transformBlock", [tree]);
},
transformFunctionBody: function(tree) {
if (tree.statements.length === 1 && tree.statements[0].type === EXPRESSION_STATEMENT) {
var transformedStatement = this.transformExpressionStatement(tree.statements[0]);
if (transformedStatement === tree.statements[0])
return tree;
if (transformedStatement.type === BLOCK)
return createFunctionBody(transformedStatement.statements);
}
return $traceurRuntime.superCall(this, $PlaceholderTransformer.prototype, "transformFunctionBody", [tree]);
},
transformMemberExpression: function(tree) {
var value = this.getValue_(tree.memberName.value);
if (value === NOT_FOUND)
return $traceurRuntime.superCall(this, $PlaceholderTransformer.prototype, "transformMemberExpression", [tree]);
var operand = this.transformAny(tree.operand);
return createMemberExpression(operand, value);
},
transformLiteralPropertyName: function(tree) {
if (tree.literalToken.type === IDENTIFIER) {
var value = this.getValue_(tree.literalToken.value);
if (value !== NOT_FOUND) {
return new LiteralPropertyName(null, convertValueToIdentifierToken(value));
}
}
return $traceurRuntime.superCall(this, $PlaceholderTransformer.prototype, "transformLiteralPropertyName", [tree]);
},
transformArgumentList: function(tree) {
if (tree.args.length === 1 && tree.args[0].type === IDENTIFIER_EXPRESSION) {
var arg0 = this.transformAny(tree.args[0]);
if (arg0 === tree.args[0])
return tree;
if (arg0.type === ARGUMENT_LIST)
return arg0;
}
return $traceurRuntime.superCall(this, $PlaceholderTransformer.prototype, "transformArgumentList", [tree]);
}
}, {}, ParseTreeTransformer);
return {
get parseExpression() {
return parseExpression;
},
get parseStatement() {
return parseStatement;
},
get parseStatements() {
return parseStatements;
},
get parsePropertyDefinition() {
return parsePropertyDefinition;
},
get PlaceholderParser() {
return PlaceholderParser;
},
get PlaceholderTransformer() {
return PlaceholderTransformer;
}
};
});
System.register("traceur@0.0.52/src/codegeneration/PrependStatements", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/PrependStatements";
var $__172 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
EXPRESSION_STATEMENT = $__172.EXPRESSION_STATEMENT,
LITERAL_EXPRESSION = $__172.LITERAL_EXPRESSION;
var STRING = System.get("traceur@0.0.52/src/syntax/TokenType").STRING;
function isStringExpressionStatement(tree) {
return tree.type === EXPRESSION_STATEMENT && tree.expression.type === LITERAL_EXPRESSION && tree.expression.literalToken.type === STRING;
}
function prependStatements(statements) {
for (var statementsToPrepend = [],
$__174 = 1; $__174 < arguments.length; $__174++)
statementsToPrepend[$__174 - 1] = arguments[$__174];
if (!statements.length)
return statementsToPrepend;
if (!statementsToPrepend.length)
return statements;
var transformed = [];
var inProlog = true;
statements.forEach((function(statement) {
var $__175;
if (inProlog && !isStringExpressionStatement(statement)) {
($__175 = transformed).push.apply($__175, $traceurRuntime.spread(statementsToPrepend));
inProlog = false;
}
transformed.push(statement);
}));
return transformed;
}
return {get prependStatements() {
return prependStatements;
}};
});
System.register("traceur@0.0.52/src/codegeneration/TempVarTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/TempVarTransformer";
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__177 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
Module = $__177.Module,
Script = $__177.Script;
var ARGUMENTS = System.get("traceur@0.0.52/src/syntax/PredefinedName").ARGUMENTS;
var VAR = System.get("traceur@0.0.52/src/syntax/TokenType").VAR;
var $__180 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createFunctionBody = $__180.createFunctionBody,
createThisExpression = $__180.createThisExpression,
createIdentifierExpression = $__180.createIdentifierExpression,
createVariableDeclaration = $__180.createVariableDeclaration,
createVariableDeclarationList = $__180.createVariableDeclarationList,
createVariableStatement = $__180.createVariableStatement;
var prependStatements = System.get("traceur@0.0.52/src/codegeneration/PrependStatements").prependStatements;
var TempVarStatement = function TempVarStatement(name, initializer) {
this.name = name;
this.initializer = initializer;
};
($traceurRuntime.createClass)(TempVarStatement, {}, {});
var TempScope = function TempScope() {
this.identifiers = [];
};
($traceurRuntime.createClass)(TempScope, {
push: function(identifier) {
this.identifiers.push(identifier);
},
pop: function() {
return this.identifiers.pop();
},
release: function(obj) {
for (var i = this.identifiers.length - 1; i >= 0; i--) {
obj.release_(this.identifiers[i]);
}
}
}, {});
var VarScope = function VarScope() {
this.thisName = null;
this.argumentName = null;
this.tempVarStatements = [];
};
($traceurRuntime.createClass)(VarScope, {
push: function(tempVarStatement) {
this.tempVarStatements.push(tempVarStatement);
},
pop: function() {
return this.tempVarStatements.pop();
},
release: function(obj) {
for (var i = this.tempVarStatements.length - 1; i >= 0; i--) {
obj.release_(this.tempVarStatements[i].name);
}
},
isEmpty: function() {
return !this.tempVarStatements.length;
},
createVariableStatement: function() {
var declarations = [];
var seenNames = Object.create(null);
for (var i = 0; i < this.tempVarStatements.length; i++) {
var $__183 = $traceurRuntime.assertObject(this.tempVarStatements[i]),
name = $__183.name,
initializer = $__183.initializer;
if (name in seenNames) {
if (seenNames[name].initializer || initializer)
throw new Error('Invalid use of TempVarTransformer');
continue;
}
seenNames[name] = true;
declarations.push(createVariableDeclaration(name, initializer));
}
return createVariableStatement(createVariableDeclarationList(VAR, declarations));
}
}, {});
var TempVarTransformer = function TempVarTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $TempVarTransformer.prototype, "constructor", []);
this.identifierGenerator = identifierGenerator;
this.tempVarStack_ = [new VarScope()];
this.tempScopeStack_ = [new TempScope()];
this.namePool_ = [];
};
var $TempVarTransformer = TempVarTransformer;
($traceurRuntime.createClass)(TempVarTransformer, {
transformStatements_: function(statements) {
this.tempVarStack_.push(new VarScope());
var transformedStatements = this.transformList(statements);
var vars = this.tempVarStack_.pop();
if (vars.isEmpty())
return transformedStatements;
var variableStatement = vars.createVariableStatement();
vars.release(this);
return prependStatements(transformedStatements, variableStatement);
},
transformScript: function(tree) {
var scriptItemList = this.transformStatements_(tree.scriptItemList);
if (scriptItemList == tree.scriptItemList) {
return tree;
}
return new Script(tree.location, scriptItemList, tree.moduleName);
},
transformModule: function(tree) {
var scriptItemList = this.transformStatements_(tree.scriptItemList);
if (scriptItemList == tree.scriptItemList) {
return tree;
}
return new Module(tree.location, scriptItemList, tree.moduleName);
},
transformFunctionBody: function(tree) {
this.pushTempScope();
var statements = this.transformStatements_(tree.statements);
this.popTempScope();
if (statements == tree.statements)
return tree;
return createFunctionBody(statements);
},
getTempIdentifier: function() {
var name = this.getName_();
this.tempScopeStack_[this.tempScopeStack_.length - 1].push(name);
return name;
},
getName_: function() {
return this.namePool_.length ? this.namePool_.pop() : this.identifierGenerator.generateUniqueIdentifier();
},
addTempVar: function() {
var initializer = arguments[0] !== (void 0) ? arguments[0] : null;
var vars = this.tempVarStack_[this.tempVarStack_.length - 1];
var name = this.getName_();
vars.push(new TempVarStatement(name, initializer));
return name;
},
addTempVarForThis: function() {
var varScope = this.tempVarStack_[this.tempVarStack_.length - 1];
return varScope.thisName || (varScope.thisName = this.addTempVar(createThisExpression()));
},
addTempVarForArguments: function() {
var varScope = this.tempVarStack_[this.tempVarStack_.length - 1];
return varScope.argumentName || (varScope.argumentName = this.addTempVar(createIdentifierExpression(ARGUMENTS)));
},
pushTempScope: function() {
this.tempScopeStack_.push(new TempScope());
},
popTempScope: function() {
this.tempScopeStack_.pop().release(this);
},
release_: function(name) {
this.namePool_.push(name);
}
}, {}, ParseTreeTransformer);
return {get TempVarTransformer() {
return TempVarTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/DestructuringTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/DestructuringTransformer";
var $__184 = Object.freeze(Object.defineProperties(["$traceurRuntime.assertObject(", ")"], {raw: {value: Object.freeze(["$traceurRuntime.assertObject(", ")"])}})),
$__185 = Object.freeze(Object.defineProperties(["", " = ", ""], {raw: {value: Object.freeze(["", " = ", ""])}})),
$__186 = Object.freeze(Object.defineProperties(["Array.prototype.slice.call(", ", ", ")"], {raw: {value: Object.freeze(["Array.prototype.slice.call(", ", ", ")"])}})),
$__187 = Object.freeze(Object.defineProperties(["(", " = ", ".", ") === void 0 ?\n ", " : ", ""], {raw: {value: Object.freeze(["(", " = ", ".", ") === void 0 ?\n ", " : ", ""])}})),
$__188 = Object.freeze(Object.defineProperties(["(", " = ", "[", "]) === void 0 ?\n ", " : ", ""], {raw: {value: Object.freeze(["(", " = ", "[", "]) === void 0 ?\n ", " : ", ""])}}));
var $__189 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
ARRAY_COMPREHENSION = $__189.ARRAY_COMPREHENSION,
ARRAY_LITERAL_EXPRESSION = $__189.ARRAY_LITERAL_EXPRESSION,
ARRAY_PATTERN = $__189.ARRAY_PATTERN,
ASSIGNMENT_ELEMENT = $__189.ASSIGNMENT_ELEMENT,
ARROW_FUNCTION_EXPRESSION = $__189.ARROW_FUNCTION_EXPRESSION,
BINDING_ELEMENT = $__189.BINDING_ELEMENT,
BINDING_IDENTIFIER = $__189.BINDING_IDENTIFIER,
BLOCK = $__189.BLOCK,
CALL_EXPRESSION = $__189.CALL_EXPRESSION,
CLASS_EXPRESSION = $__189.CLASS_EXPRESSION,
COMPUTED_PROPERTY_NAME = $__189.COMPUTED_PROPERTY_NAME,
FUNCTION_EXPRESSION = $__189.FUNCTION_EXPRESSION,
GENERATOR_COMPREHENSION = $__189.GENERATOR_COMPREHENSION,
IDENTIFIER_EXPRESSION = $__189.IDENTIFIER_EXPRESSION,
LITERAL_EXPRESSION = $__189.LITERAL_EXPRESSION,
MEMBER_EXPRESSION = $__189.MEMBER_EXPRESSION,
MEMBER_LOOKUP_EXPRESSION = $__189.MEMBER_LOOKUP_EXPRESSION,
OBJECT_LITERAL_EXPRESSION = $__189.OBJECT_LITERAL_EXPRESSION,
OBJECT_PATTERN = $__189.OBJECT_PATTERN,
OBJECT_PATTERN_FIELD = $__189.OBJECT_PATTERN_FIELD,
PAREN_EXPRESSION = $__189.PAREN_EXPRESSION,
THIS_EXPRESSION = $__189.THIS_EXPRESSION,
VARIABLE_DECLARATION_LIST = $__189.VARIABLE_DECLARATION_LIST;
var $__190 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AssignmentElement = $__190.AssignmentElement,
BindingElement = $__190.BindingElement,
Catch = $__190.Catch,
ForInStatement = $__190.ForInStatement,
ForOfStatement = $__190.ForOfStatement;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__192 = System.get("traceur@0.0.52/src/syntax/TokenType"),
EQUAL = $__192.EQUAL,
LET = $__192.LET,
REGULAR_EXPRESSION = $__192.REGULAR_EXPRESSION,
VAR = $__192.VAR;
var $__193 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createAssignmentExpression = $__193.createAssignmentExpression,
createBindingIdentifier = $__193.createBindingIdentifier,
createBlock = $__193.createBlock,
createCommaExpression = $__193.createCommaExpression,
createExpressionStatement = $__193.createExpressionStatement,
createFunctionBody = $__193.createFunctionBody,
createIdentifierExpression = $__193.createIdentifierExpression,
createMemberExpression = $__193.createMemberExpression,
createMemberLookupExpression = $__193.createMemberLookupExpression,
createNumberLiteral = $__193.createNumberLiteral,
createParenExpression = $__193.createParenExpression,
createVariableDeclaration = $__193.createVariableDeclaration,
createVariableDeclarationList = $__193.createVariableDeclarationList,
createVariableStatement = $__193.createVariableStatement;
var options = System.get("traceur@0.0.52/src/Options").options;
var parseExpression = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseExpression;
var prependStatements = System.get("traceur@0.0.52/src/codegeneration/PrependStatements").prependStatements;
var Desugaring = function Desugaring(rvalue) {
this.rvalue = rvalue;
};
($traceurRuntime.createClass)(Desugaring, {}, {});
var AssignmentExpressionDesugaring = function AssignmentExpressionDesugaring(rvalue) {
$traceurRuntime.superCall(this, $AssignmentExpressionDesugaring.prototype, "constructor", [rvalue]);
this.expressions = [];
};
var $AssignmentExpressionDesugaring = AssignmentExpressionDesugaring;
($traceurRuntime.createClass)(AssignmentExpressionDesugaring, {assign: function(lvalue, rvalue) {
lvalue = lvalue instanceof AssignmentElement ? lvalue.assignment : lvalue;
this.expressions.push(createAssignmentExpression(lvalue, rvalue));
}}, {}, Desugaring);
var VariableDeclarationDesugaring = function VariableDeclarationDesugaring(rvalue) {
$traceurRuntime.superCall(this, $VariableDeclarationDesugaring.prototype, "constructor", [rvalue]);
this.declarations = [];
};
var $VariableDeclarationDesugaring = VariableDeclarationDesugaring;
($traceurRuntime.createClass)(VariableDeclarationDesugaring, {assign: function(lvalue, rvalue) {
var binding = lvalue instanceof BindingElement ? lvalue.binding : createBindingIdentifier(lvalue);
this.declarations.push(createVariableDeclaration(binding, rvalue));
}}, {}, Desugaring);
function staticallyKnownObject(tree) {
switch (tree.type) {
case OBJECT_LITERAL_EXPRESSION:
case ARRAY_LITERAL_EXPRESSION:
case ARRAY_COMPREHENSION:
case GENERATOR_COMPREHENSION:
case ARROW_FUNCTION_EXPRESSION:
case FUNCTION_EXPRESSION:
case CLASS_EXPRESSION:
case THIS_EXPRESSION:
return true;
case LITERAL_EXPRESSION:
return tree.literalToken.type === REGULAR_EXPRESSION;
}
return false;
}
var DestructuringTransformer = function DestructuringTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $DestructuringTransformer.prototype, "constructor", [identifierGenerator]);
this.parameterDeclarations = null;
};
var $DestructuringTransformer = DestructuringTransformer;
($traceurRuntime.createClass)(DestructuringTransformer, {
transformArrayPattern: function(tree) {
throw new Error('unreachable');
},
transformObjectPattern: function(tree) {
throw new Error('unreachable');
},
transformBinaryExpression: function(tree) {
this.pushTempScope();
var rv;
if (tree.operator.type == EQUAL && tree.left.isPattern()) {
rv = this.transformAny(this.desugarAssignment_(tree.left, tree.right));
} else {
rv = $traceurRuntime.superCall(this, $DestructuringTransformer.prototype, "transformBinaryExpression", [tree]);
}
this.popTempScope();
return rv;
},
desugarAssignment_: function(lvalue, rvalue) {
var tempIdent = createIdentifierExpression(this.addTempVar());
var desugaring = new AssignmentExpressionDesugaring(tempIdent);
this.desugarPattern_(desugaring, lvalue);
desugaring.expressions.unshift(this.createGuardedAssignment(tempIdent, rvalue));
desugaring.expressions.push(tempIdent);
return createParenExpression(createCommaExpression(desugaring.expressions));
},
transformVariableDeclarationList: function(tree) {
var $__197 = this;
if (!this.destructuringInDeclaration_(tree)) {
return $traceurRuntime.superCall(this, $DestructuringTransformer.prototype, "transformVariableDeclarationList", [tree]);
}
this.pushTempScope();
var desugaredDeclarations = [];
tree.declarations.forEach((function(declaration) {
var $__199;
if (declaration.lvalue.isPattern()) {
($__199 = desugaredDeclarations).push.apply($__199, $traceurRuntime.spread($__197.desugarVariableDeclaration_(declaration)));
} else {
desugaredDeclarations.push(declaration);
}
}));
var transformedTree = this.transformVariableDeclarationList(createVariableDeclarationList(tree.declarationType, desugaredDeclarations));
this.popTempScope();
return transformedTree;
},
transformForInStatement: function(tree) {
return this.transformForInOrOf_(tree, $traceurRuntime.superGet(this, $DestructuringTransformer.prototype, "transformForInStatement"), ForInStatement);
},
transformForOfStatement: function(tree) {
return this.transformForInOrOf_(tree, $traceurRuntime.superGet(this, $DestructuringTransformer.prototype, "transformForOfStatement"), ForOfStatement);
},
transformForInOrOf_: function(tree, superMethod, constr) {
var $__199;
if (!tree.initializer.isPattern() && (tree.initializer.type !== VARIABLE_DECLARATION_LIST || !this.destructuringInDeclaration_(tree.initializer))) {
return superMethod.call(this, tree);
}
this.pushTempScope();
var declarationType,
lvalue;
if (tree.initializer.isPattern()) {
declarationType = null;
lvalue = tree.initializer;
} else {
declarationType = tree.initializer.declarationType;
lvalue = tree.initializer.declarations[0].lvalue;
}
var statements = [];
var binding = this.desugarBinding_(lvalue, statements, declarationType);
var initializer = createVariableDeclarationList(VAR, binding, null);
var collection = this.transformAny(tree.collection);
var body = this.transformAny(tree.body);
if (body.type === BLOCK)
($__199 = statements).push.apply($__199, $traceurRuntime.spread(body.statements));
else
statements.push(body);
body = createBlock(statements);
this.popTempScope();
return new constr(tree.location, initializer, collection, body);
},
transformAssignmentElement: function(tree) {
throw new Error('unreachable');
},
transformBindingElement: function(tree) {
if (!tree.binding.isPattern() || tree.initializer)
return tree;
if (this.parameterDeclarations === null) {
this.parameterDeclarations = [];
this.pushTempScope();
}
var varName = this.getTempIdentifier();
var binding = createBindingIdentifier(varName);
var initializer = createIdentifierExpression(varName);
var decl = createVariableDeclaration(tree.binding, initializer);
this.parameterDeclarations.push(decl);
return new BindingElement(null, binding, null);
},
transformFunctionBody: function(tree) {
if (this.parameterDeclarations === null)
return $traceurRuntime.superCall(this, $DestructuringTransformer.prototype, "transformFunctionBody", [tree]);
var list = createVariableDeclarationList(VAR, this.parameterDeclarations);
var statement = createVariableStatement(list);
var statements = prependStatements(tree.statements, statement);
var newBody = createFunctionBody(statements);
this.parameterDeclarations = null;
var result = $traceurRuntime.superCall(this, $DestructuringTransformer.prototype, "transformFunctionBody", [newBody]);
this.popTempScope();
return result;
},
transformCatch: function(tree) {
var $__199;
if (!tree.binding.isPattern())
return $traceurRuntime.superCall(this, $DestructuringTransformer.prototype, "transformCatch", [tree]);
var body = this.transformAny(tree.catchBody);
var statements = [];
var kind = options.blockBinding ? LET : VAR;
var binding = this.desugarBinding_(tree.binding, statements, kind);
($__199 = statements).push.apply($__199, $traceurRuntime.spread(body.statements));
return new Catch(tree.location, binding, createBlock(statements));
},
desugarBinding_: function(bindingTree, statements, declarationType) {
var varName = this.getTempIdentifier();
var binding = createBindingIdentifier(varName);
var idExpr = createIdentifierExpression(varName);
var desugaring;
if (declarationType === null)
desugaring = new AssignmentExpressionDesugaring(idExpr);
else
desugaring = new VariableDeclarationDesugaring(idExpr);
this.desugarPattern_(desugaring, bindingTree);
if (declarationType === null) {
statements.push(createExpressionStatement(createCommaExpression(desugaring.expressions)));
} else {
statements.push(createVariableStatement(this.transformVariableDeclarationList(createVariableDeclarationList(declarationType, desugaring.declarations))));
}
return binding;
},
destructuringInDeclaration_: function(tree) {
return tree.declarations.some((function(declaration) {
return declaration.lvalue.isPattern();
}));
},
createGuardedExpression: function(tree) {
if (staticallyKnownObject(tree))
return tree;
return parseExpression($__184, tree);
},
createGuardedAssignment: function(lvalue, rvalue) {
return parseExpression($__185, lvalue, this.createGuardedExpression(rvalue));
},
desugarVariableDeclaration_: function(tree) {
var tempRValueName = this.getTempIdentifier();
var tempRValueIdent = createIdentifierExpression(tempRValueName);
var desugaring;
var initializer;
switch (tree.initializer.type) {
case ARRAY_LITERAL_EXPRESSION:
case CALL_EXPRESSION:
case IDENTIFIER_EXPRESSION:
case LITERAL_EXPRESSION:
case MEMBER_EXPRESSION:
case MEMBER_LOOKUP_EXPRESSION:
case OBJECT_LITERAL_EXPRESSION:
case PAREN_EXPRESSION:
initializer = tree.initializer;
default:
desugaring = new VariableDeclarationDesugaring(tempRValueIdent);
desugaring.assign(desugaring.rvalue, this.createGuardedExpression(tree.initializer));
var initializerFound = this.desugarPattern_(desugaring, tree.lvalue);
if (initializerFound || desugaring.declarations.length > 2)
return desugaring.declarations;
initializer = this.createGuardedExpression(initializer || tree.initializer);
desugaring = new VariableDeclarationDesugaring(initializer);
this.desugarPattern_(desugaring, tree.lvalue);
return desugaring.declarations;
}
},
desugarPattern_: function(desugaring, tree) {
var $__197 = this;
var initializerFound = false;
switch (tree.type) {
case ARRAY_PATTERN:
var pattern = tree;
for (var i = 0; i < pattern.elements.length; i++) {
var lvalue = pattern.elements[i];
if (lvalue === null) {
continue;
} else if (lvalue.isSpreadPatternElement()) {
desugaring.assign(lvalue.lvalue, parseExpression($__186, desugaring.rvalue, i));
} else {
if (lvalue.initializer)
initializerFound = true;
desugaring.assign(lvalue, this.createConditionalMemberLookupExpression(desugaring.rvalue, createNumberLiteral(i), lvalue.initializer));
}
}
break;
case OBJECT_PATTERN:
var pattern = tree;
var elementHelper = (function(lvalue, initializer) {
if (initializer)
initializerFound = true;
var lookup = $__197.createConditionalMemberExpression(desugaring.rvalue, lvalue, initializer);
desugaring.assign(lvalue, lookup);
});
pattern.fields.forEach((function(field) {
var lookup;
switch (field.type) {
case ASSIGNMENT_ELEMENT:
elementHelper(field.assignment, field.initializer);
break;
case BINDING_ELEMENT:
elementHelper(field.binding, field.initializer);
break;
case OBJECT_PATTERN_FIELD:
if (field.element.initializer)
initializerFound = true;
var name = field.name;
lookup = $__197.createConditionalMemberExpression(desugaring.rvalue, name, field.element.initializer);
desugaring.assign(field.element, lookup);
break;
default:
throw Error('unreachable');
}
}));
break;
case PAREN_EXPRESSION:
return this.desugarPattern_(desugaring, tree.expression);
default:
throw new Error('unreachable');
}
if (desugaring instanceof VariableDeclarationDesugaring && desugaring.declarations.length === 0) {
desugaring.assign(createBindingIdentifier(this.getTempIdentifier()), desugaring.rvalue);
}
return initializerFound;
},
createConditionalMemberExpression: function(rvalue, name, initializer) {
if (name.type === COMPUTED_PROPERTY_NAME) {
return this.createConditionalMemberLookupExpression(rvalue, name.expression, initializer);
}
var token;
switch (name.type) {
case BINDING_IDENTIFIER:
case IDENTIFIER_EXPRESSION:
token = name.identifierToken;
break;
default:
token = name.literalToken;
}
if (!initializer)
return createMemberExpression(rvalue, token);
var tempIdent = createIdentifierExpression(this.addTempVar());
return parseExpression($__187, tempIdent, rvalue, token, initializer, tempIdent);
},
createConditionalMemberLookupExpression: function(rvalue, index, initializer) {
if (!initializer)
return createMemberLookupExpression(rvalue, index);
var tempIdent = createIdentifierExpression(this.addTempVar());
return parseExpression($__188, tempIdent, rvalue, index, initializer, tempIdent);
}
}, {}, TempVarTransformer);
return {get DestructuringTransformer() {
return DestructuringTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/ModuleSymbol", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/ModuleSymbol";
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var ExportsList = function ExportsList(normalizedName) {
this.exports_ = Object.create(null);
if (normalizedName !== null)
this.normalizedName = normalizedName.replace(/\\/g, '/');
else
this.normalizedName = null;
};
($traceurRuntime.createClass)(ExportsList, {
addExport: function(name, tree) {
assert(!this.exports_[name]);
this.exports_[name] = tree;
},
getExport: function(name) {
return this.exports_[name];
},
getExports: function() {
return Object.keys(this.exports_);
}
}, {});
var ModuleDescription = function ModuleDescription(normalizedName, module) {
var $__201 = this;
$traceurRuntime.superCall(this, $ModuleDescription.prototype, "constructor", [normalizedName]);
Object.getOwnPropertyNames(module).forEach((function(name) {
$__201.addExport(name, true);
}));
};
var $ModuleDescription = ModuleDescription;
($traceurRuntime.createClass)(ModuleDescription, {}, {}, ExportsList);
var ModuleSymbol = function ModuleSymbol(tree, normalizedName) {
$traceurRuntime.superCall(this, $ModuleSymbol.prototype, "constructor", [normalizedName]);
this.tree = tree;
this.imports_ = Object.create(null);
};
var $ModuleSymbol = ModuleSymbol;
($traceurRuntime.createClass)(ModuleSymbol, {
addImport: function(name, tree) {
assert(!this.imports_[name]);
this.imports_[name] = tree;
},
getImport: function(name) {
return this.imports_[name];
}
}, {}, ExportsList);
return {
get ModuleDescription() {
return ModuleDescription;
},
get ModuleSymbol() {
return ModuleSymbol;
}
};
});
System.register("traceur@0.0.52/src/codegeneration/module/ModuleVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/ModuleVisitor";
var ModuleDescription = System.get("traceur@0.0.52/src/codegeneration/module/ModuleSymbol").ModuleDescription;
var ParseTreeVisitor = System.get("traceur@0.0.52/src/syntax/ParseTreeVisitor").ParseTreeVisitor;
var $__205 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
MODULE_DECLARATION = $__205.MODULE_DECLARATION,
EXPORT_DECLARATION = $__205.EXPORT_DECLARATION,
IMPORT_DECLARATION = $__205.IMPORT_DECLARATION;
var ModuleVisitor = function ModuleVisitor(reporter, loader, moduleSymbol) {
this.reporter = reporter;
this.loader_ = loader;
this.moduleSymbol = moduleSymbol;
};
($traceurRuntime.createClass)(ModuleVisitor, {
getModuleDescriptionFromCodeUnit_: function(name, codeUnitToModuleInfo) {
var referrer = this.moduleSymbol.normalizedName;
var codeUnit = this.loader_.getCodeUnitForModuleSpecifier(name, referrer);
var moduleDescription = codeUnitToModuleInfo(codeUnit);
if (!moduleDescription) {
var msg = (name + " is not a module, required by " + referrer);
this.reportError(codeUnit.metadata.tree, msg);
return null;
}
return moduleDescription;
},
getModuleSymbolForModuleSpecifier: function(name) {
return this.getModuleDescriptionFromCodeUnit_(name, (function(codeUnit) {
return codeUnit.metadata.moduleSymbol;
}));
},
getModuleDescriptionForModuleSpecifier: function(name) {
return this.getModuleDescriptionFromCodeUnit_(name, (function(codeUnit) {
var moduleDescription = codeUnit.metadata.moduleSymbol;
if (!moduleDescription && codeUnit.result) {
moduleDescription = new ModuleDescription(codeUnit.normalizedName, codeUnit.result);
}
return moduleDescription;
}));
},
visitFunctionDeclaration: function(tree) {},
visitFunctionExpression: function(tree) {},
visitFunctionBody: function(tree) {},
visitBlock: function(tree) {},
visitClassDeclaration: function(tree) {},
visitClassExpression: function(tree) {},
visitModuleElement_: function(element) {
switch (element.type) {
case MODULE_DECLARATION:
case EXPORT_DECLARATION:
case IMPORT_DECLARATION:
this.visitAny(element);
}
},
visitScript: function(tree) {
tree.scriptItemList.forEach(this.visitModuleElement_, this);
},
visitModule: function(tree) {
tree.scriptItemList.forEach(this.visitModuleElement_, this);
},
reportError: function(tree, message) {
this.reporter.reportError(tree.location.start, message);
}
}, {}, ParseTreeVisitor);
return {get ModuleVisitor() {
return ModuleVisitor;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/ExportVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/ExportVisitor";
var ModuleVisitor = System.get("traceur@0.0.52/src/codegeneration/module/ModuleVisitor").ModuleVisitor;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var ExportVisitor = function ExportVisitor(reporter, loaderHooks, moduleSymbol) {
$traceurRuntime.superCall(this, $ExportVisitor.prototype, "constructor", [reporter, loaderHooks, moduleSymbol]);
this.inExport_ = false;
this.moduleSpecifier = null;
};
var $ExportVisitor = ExportVisitor;
($traceurRuntime.createClass)(ExportVisitor, {
addExport_: function(name, tree) {
assert(typeof name == 'string');
if (this.inExport_)
this.addExport(name, tree);
},
addExport: function(name, tree) {
var moduleSymbol = this.moduleSymbol;
var existingExport = moduleSymbol.getExport(name);
if (existingExport) {
this.reportError(tree, ("Duplicate export. '" + name + "' was previously ") + ("exported at " + existingExport.location.start));
} else {
moduleSymbol.addExport(name, tree);
}
},
visitClassDeclaration: function(tree) {
this.addExport_(tree.name.identifierToken.value, tree);
},
visitExportDeclaration: function(tree) {
this.inExport_ = true;
this.visitAny(tree.declaration);
this.inExport_ = false;
},
visitNamedExport: function(tree) {
this.moduleSpecifier = tree.moduleSpecifier;
this.visitAny(tree.specifierSet);
this.moduleSpecifier = null;
},
visitExportDefault: function(tree) {
this.addExport_('default', tree);
},
visitExportSpecifier: function(tree) {
this.addExport_((tree.rhs || tree.lhs).value, tree);
},
visitExportStar: function(tree) {
var $__209 = this;
var name = this.moduleSpecifier.token.processedValue;
var moduleDescription = this.getModuleDescriptionForModuleSpecifier(name);
if (moduleDescription) {
moduleDescription.getExports().forEach((function(name) {
$__209.addExport(name, tree);
}));
}
},
visitFunctionDeclaration: function(tree) {
this.addExport_(tree.name.identifierToken.value, tree);
},
visitModuleDeclaration: function(tree) {
this.addExport_(tree.identifier.value, tree);
},
visitVariableDeclaration: function(tree) {
this.addExport_(tree.lvalue.identifierToken.value, tree);
}
}, {}, ModuleVisitor);
return {get ExportVisitor() {
return ExportVisitor;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/DirectExportVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/DirectExportVisitor";
var ExportVisitor = System.get("traceur@0.0.52/src/codegeneration/module/ExportVisitor").ExportVisitor;
var DirectExportVisitor = function DirectExportVisitor() {
$traceurRuntime.superCall(this, $DirectExportVisitor.prototype, "constructor", [null, null, null]);
this.namedExports = [];
this.starExports = [];
};
var $DirectExportVisitor = DirectExportVisitor;
($traceurRuntime.createClass)(DirectExportVisitor, {
addExport: function(name, tree) {
this.namedExports.push({
name: name,
tree: tree,
moduleSpecifier: this.moduleSpecifier
});
},
visitExportStar: function(tree) {
this.starExports.push(this.moduleSpecifier);
},
hasExports: function() {
return this.namedExports.length != 0 || this.starExports.length != 0;
}
}, {}, ExportVisitor);
return {get DirectExportVisitor() {
return DirectExportVisitor;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ModuleTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ModuleTransformer";
var $__213 = Object.freeze(Object.defineProperties(["var __moduleName = ", ";"], {raw: {value: Object.freeze(["var __moduleName = ", ";"])}})),
$__214 = Object.freeze(Object.defineProperties(["function() {\n ", "\n }"], {raw: {value: Object.freeze(["function() {\n ", "\n }"])}})),
$__215 = Object.freeze(Object.defineProperties(["$traceurRuntime.ModuleStore.getAnonymousModule(\n ", ");"], {raw: {value: Object.freeze(["$traceurRuntime.ModuleStore.getAnonymousModule(\n ", ");"])}})),
$__216 = Object.freeze(Object.defineProperties(["System.register(", ", [], ", ");"], {raw: {value: Object.freeze(["System.register(", ", [], ", ");"])}})),
$__217 = Object.freeze(Object.defineProperties(["get ", "() { return ", "; }"], {raw: {value: Object.freeze(["get ", "() { return ", "; }"])}})),
$__218 = Object.freeze(Object.defineProperties(["$traceurRuntime.exportStar(", ")"], {raw: {value: Object.freeze(["$traceurRuntime.exportStar(", ")"])}})),
$__219 = Object.freeze(Object.defineProperties(["return ", ""], {raw: {value: Object.freeze(["return ", ""])}})),
$__220 = Object.freeze(Object.defineProperties(["var $__default = ", ""], {raw: {value: Object.freeze(["var $__default = ", ""])}})),
$__221 = Object.freeze(Object.defineProperties(["var $__default = ", ""], {raw: {value: Object.freeze(["var $__default = ", ""])}})),
$__222 = Object.freeze(Object.defineProperties(["System.get(", ")"], {raw: {value: Object.freeze(["System.get(", ")"])}}));
var $__223 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AnonBlock = $__223.AnonBlock,
BindingElement = $__223.BindingElement,
BindingIdentifier = $__223.BindingIdentifier,
EmptyStatement = $__223.EmptyStatement,
LiteralPropertyName = $__223.LiteralPropertyName,
ObjectPattern = $__223.ObjectPattern,
ObjectPatternField = $__223.ObjectPatternField,
Script = $__223.Script;
var DestructuringTransformer = System.get("traceur@0.0.52/src/codegeneration/DestructuringTransformer").DestructuringTransformer;
var DirectExportVisitor = System.get("traceur@0.0.52/src/codegeneration/module/DirectExportVisitor").DirectExportVisitor;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__227 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
CLASS_DECLARATION = $__227.CLASS_DECLARATION,
EXPORT_DEFAULT = $__227.EXPORT_DEFAULT,
EXPORT_SPECIFIER = $__227.EXPORT_SPECIFIER,
FUNCTION_DECLARATION = $__227.FUNCTION_DECLARATION,
IMPORT_SPECIFIER_SET = $__227.IMPORT_SPECIFIER_SET;
var VAR = System.get("traceur@0.0.52/src/syntax/TokenType").VAR;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var $__230 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArgumentList = $__230.createArgumentList,
createBindingIdentifier = $__230.createBindingIdentifier,
createExpressionStatement = $__230.createExpressionStatement,
createIdentifierExpression = $__230.createIdentifierExpression,
createIdentifierToken = $__230.createIdentifierToken,
createMemberExpression = $__230.createMemberExpression,
createObjectLiteralExpression = $__230.createObjectLiteralExpression,
createUseStrictDirective = $__230.createUseStrictDirective,
createVariableStatement = $__230.createVariableStatement;
var $__231 = System.get("traceur@0.0.52/src/Options"),
parseOptions = $__231.parseOptions,
transformOptions = $__231.transformOptions;
var $__232 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__232.parseExpression,
parsePropertyDefinition = $__232.parsePropertyDefinition,
parseStatement = $__232.parseStatement,
parseStatements = $__232.parseStatements;
var DestructImportVarStatement = function DestructImportVarStatement() {
$traceurRuntime.defaultSuperCall(this, $DestructImportVarStatement.prototype, arguments);
};
var $DestructImportVarStatement = DestructImportVarStatement;
($traceurRuntime.createClass)(DestructImportVarStatement, {createGuardedExpression: function(tree) {
return tree;
}}, {}, DestructuringTransformer);
var ModuleTransformer = function ModuleTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $ModuleTransformer.prototype, "constructor", [identifierGenerator]);
this.exportVisitor_ = new DirectExportVisitor();
this.moduleSpecifierKind_ = null;
this.moduleName = null;
};
var $ModuleTransformer = ModuleTransformer;
($traceurRuntime.createClass)(ModuleTransformer, {
getTempVarNameForModuleName: function(moduleName) {
return '$__' + moduleName.replace(/[^a-zA-Z0-9$]/g, function(c) {
return '_' + c.charCodeAt(0) + '_';
}) + '__';
},
getTempVarNameForModuleSpecifier: function(moduleSpecifier) {
var normalizedName = System.normalize(moduleSpecifier.token.processedValue, this.moduleName);
return this.getTempVarNameForModuleName(normalizedName);
},
transformScript: function(tree) {
this.moduleName = tree.moduleName;
return $traceurRuntime.superCall(this, $ModuleTransformer.prototype, "transformScript", [tree]);
},
transformModule: function(tree) {
this.moduleName = tree.moduleName;
this.pushTempScope();
var statements = this.transformList(tree.scriptItemList);
statements = this.appendExportStatement(statements);
this.popTempScope();
statements = this.wrapModule(this.moduleProlog().concat(statements));
return new Script(tree.location, statements);
},
moduleProlog: function() {
var statements = [createUseStrictDirective()];
if (this.moduleName)
statements.push(parseStatement($__213, this.moduleName));
return statements;
},
wrapModule: function(statements) {
var functionExpression = parseExpression($__214, statements);
if (this.moduleName === null) {
return parseStatements($__215, functionExpression);
}
return parseStatements($__216, this.moduleName, functionExpression);
},
getGetterExport: function($__235) {
var $__236 = $traceurRuntime.assertObject($__235),
name = $__236.name,
tree = $__236.tree,
moduleSpecifier = $__236.moduleSpecifier;
var returnExpression;
switch (tree.type) {
case EXPORT_DEFAULT:
returnExpression = createIdentifierExpression('$__default');
break;
case EXPORT_SPECIFIER:
if (moduleSpecifier) {
var idName = this.getTempVarNameForModuleSpecifier(moduleSpecifier);
returnExpression = createMemberExpression(idName, tree.lhs);
} else {
returnExpression = createIdentifierExpression(tree.lhs);
}
break;
default:
returnExpression = createIdentifierExpression(name);
break;
}
return parsePropertyDefinition($__217, name, returnExpression);
},
getExportProperties: function() {
var $__233 = this;
return this.exportVisitor_.namedExports.map((function(exp) {
return $__233.getGetterExport(exp);
})).concat(this.exportVisitor_.namedExports.map((function(exp) {
return $__233.getSetterExport(exp);
}))).filter((function(e) {
return e;
}));
},
getSetterExport: function($__235) {
var $__236 = $traceurRuntime.assertObject($__235),
name = $__236.name,
tree = $__236.tree,
moduleSpecifier = $__236.moduleSpecifier;
return null;
},
getExportObject: function() {
var $__233 = this;
var exportObject = createObjectLiteralExpression(this.getExportProperties());
if (this.exportVisitor_.starExports.length) {
var starExports = this.exportVisitor_.starExports;
var starIdents = starExports.map((function(moduleSpecifier) {
return createIdentifierExpression($__233.getTempVarNameForModuleSpecifier(moduleSpecifier));
}));
var args = createArgumentList($traceurRuntime.spread([exportObject], starIdents));
return parseExpression($__218, args);
}
return exportObject;
},
appendExportStatement: function(statements) {
var exportObject = this.getExportObject();
statements.push(parseStatement($__219, exportObject));
return statements;
},
hasExports: function() {
return this.exportVisitor_.hasExports();
},
transformExportDeclaration: function(tree) {
this.exportVisitor_.visitAny(tree);
return this.transformAny(tree.declaration);
},
transformExportDefault: function(tree) {
switch (tree.expression.type) {
case CLASS_DECLARATION:
case FUNCTION_DECLARATION:
var nameBinding = tree.expression.name;
var name = createIdentifierExpression(nameBinding.identifierToken);
return new AnonBlock(null, [tree.expression, parseStatement($__220, name)]);
}
return parseStatement($__221, tree.expression);
},
transformNamedExport: function(tree) {
var moduleSpecifier = tree.moduleSpecifier;
if (moduleSpecifier) {
var expression = this.transformAny(moduleSpecifier);
var idName = this.getTempVarNameForModuleSpecifier(moduleSpecifier);
return createVariableStatement(VAR, idName, expression);
}
return new EmptyStatement(null);
},
transformModuleSpecifier: function(tree) {
assert(this.moduleName);
var name = tree.token.processedValue;
var normalizedName = System.normalize(name, this.moduleName);
return parseExpression($__222, normalizedName);
},
transformModuleDeclaration: function(tree) {
this.moduleSpecifierKind_ = 'module';
var initializer = this.transformAny(tree.expression);
return createVariableStatement(VAR, tree.identifier, initializer);
},
transformImportedBinding: function(tree) {
var bindingElement = new BindingElement(tree.location, tree.binding, null);
var name = new LiteralPropertyName(null, createIdentifierToken('default'));
return new ObjectPattern(null, [new ObjectPatternField(null, name, bindingElement)]);
},
transformImportDeclaration: function(tree) {
this.moduleSpecifierKind_ = 'import';
if (!tree.importClause || (tree.importClause.type === IMPORT_SPECIFIER_SET && tree.importClause.specifiers.length === 0)) {
return createExpressionStatement(this.transformAny(tree.moduleSpecifier));
}
var binding = this.transformAny(tree.importClause);
var initializer = this.transformAny(tree.moduleSpecifier);
var varStatement = createVariableStatement(VAR, binding, initializer);
if (transformOptions.destructuring || !parseOptions.destructuring) {
var destructuringTransformer = new DestructImportVarStatement(this.identifierGenerator);
varStatement = varStatement.transform(destructuringTransformer);
}
return varStatement;
},
transformImportSpecifierSet: function(tree) {
var fields = this.transformList(tree.specifiers);
return new ObjectPattern(null, fields);
},
transformImportSpecifier: function(tree) {
if (tree.rhs) {
var binding = new BindingIdentifier(tree.location, tree.rhs);
var bindingElement = new BindingElement(tree.location, binding, null);
var name = new LiteralPropertyName(tree.lhs.location, tree.lhs);
return new ObjectPatternField(tree.location, name, bindingElement);
}
return new BindingElement(tree.location, createBindingIdentifier(tree.lhs), null);
}
}, {}, TempVarTransformer);
return {get ModuleTransformer() {
return ModuleTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/globalThis", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/globalThis";
var $__237 = Object.freeze(Object.defineProperties(["Reflect.global"], {raw: {value: Object.freeze(["Reflect.global"])}}));
var parseExpression = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseExpression;
var expr;
function globalThis() {
if (!expr)
expr = parseExpression($__237);
return expr;
}
var $__default = globalThis;
return {get default() {
return $__default;
}};
});
System.register("traceur@0.0.52/src/codegeneration/FindInFunctionScope", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/FindInFunctionScope";
var FindVisitor = System.get("traceur@0.0.52/src/codegeneration/FindVisitor").FindVisitor;
var FindInFunctionScope = function FindInFunctionScope() {
$traceurRuntime.defaultSuperCall(this, $FindInFunctionScope.prototype, arguments);
};
var $FindInFunctionScope = FindInFunctionScope;
($traceurRuntime.createClass)(FindInFunctionScope, {
visitFunctionDeclaration: function(tree) {},
visitFunctionExpression: function(tree) {},
visitSetAccessor: function(tree) {},
visitGetAccessor: function(tree) {},
visitPropertyMethodAssignment: function(tree) {}
}, {}, FindVisitor);
return {get FindInFunctionScope() {
return FindInFunctionScope;
}};
});
System.register("traceur@0.0.52/src/codegeneration/scopeContainsThis", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/scopeContainsThis";
var FindInFunctionScope = System.get("traceur@0.0.52/src/codegeneration/FindInFunctionScope").FindInFunctionScope;
var FindThis = function FindThis() {
$traceurRuntime.defaultSuperCall(this, $FindThis.prototype, arguments);
};
var $FindThis = FindThis;
($traceurRuntime.createClass)(FindThis, {visitThisExpression: function(tree) {
this.found = true;
}}, {}, FindInFunctionScope);
function scopeContainsThis(tree) {
var visitor = new FindThis(tree);
return visitor.found;
}
var $__default = scopeContainsThis;
return {get default() {
return $__default;
}};
});
System.register("traceur@0.0.52/src/codegeneration/AmdTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/AmdTransformer";
var $__243 = Object.freeze(Object.defineProperties(["__esModule: true"], {raw: {value: Object.freeze(["__esModule: true"])}})),
$__244 = Object.freeze(Object.defineProperties(["if (!", " || !", ".__esModule)\n ", " = { 'default': ", " }"], {raw: {value: Object.freeze(["if (!", " || !", ".__esModule)\n ", " = { 'default': ", " }"])}})),
$__245 = Object.freeze(Object.defineProperties(["function(", ") {\n ", "\n }"], {raw: {value: Object.freeze(["function(", ") {\n ", "\n }"])}})),
$__246 = Object.freeze(Object.defineProperties(["", ".bind(", ")"], {raw: {value: Object.freeze(["", ".bind(", ")"])}})),
$__247 = Object.freeze(Object.defineProperties(["define(", ", ", ", ", ");"], {raw: {value: Object.freeze(["define(", ", ", ", ", ");"])}})),
$__248 = Object.freeze(Object.defineProperties(["define(", ", ", ");"], {raw: {value: Object.freeze(["define(", ", ", ");"])}}));
var ModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/ModuleTransformer").ModuleTransformer;
var $__250 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createBindingIdentifier = $__250.createBindingIdentifier,
createIdentifierExpression = $__250.createIdentifierExpression;
var globalThis = System.get("traceur@0.0.52/src/codegeneration/globalThis").default;
var $__252 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__252.parseExpression,
parseStatement = $__252.parseStatement,
parseStatements = $__252.parseStatements,
parsePropertyDefinition = $__252.parsePropertyDefinition;
var scopeContainsThis = System.get("traceur@0.0.52/src/codegeneration/scopeContainsThis").default;
var AmdTransformer = function AmdTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $AmdTransformer.prototype, "constructor", [identifierGenerator]);
this.dependencies = [];
};
var $AmdTransformer = AmdTransformer;
($traceurRuntime.createClass)(AmdTransformer, {
getExportProperties: function() {
var properties = $traceurRuntime.superCall(this, $AmdTransformer.prototype, "getExportProperties", []);
if (this.exportVisitor_.hasExports())
properties.push(parsePropertyDefinition($__243));
return properties;
},
moduleProlog: function() {
var locals = this.dependencies.map((function(dep) {
var local = createIdentifierExpression(dep.local);
return parseStatement($__244, local, local, local, local);
}));
return $traceurRuntime.superCall(this, $AmdTransformer.prototype, "moduleProlog", []).concat(locals);
},
wrapModule: function(statements) {
var depPaths = this.dependencies.map((function(dep) {
return dep.path;
}));
var depLocals = this.dependencies.map((function(dep) {
return dep.local;
}));
var hasTopLevelThis = statements.some(scopeContainsThis);
var func = parseExpression($__245, depLocals, statements);
if (hasTopLevelThis)
func = parseExpression($__246, func, globalThis());
if (this.moduleName) {
return parseStatements($__247, this.moduleName, depPaths, func);
} else {
return parseStatements($__248, depPaths, func);
}
},
transformModuleSpecifier: function(tree) {
var localName = this.getTempIdentifier();
this.dependencies.push({
path: tree.token,
local: localName
});
return createBindingIdentifier(localName);
}
}, {}, ModuleTransformer);
return {get AmdTransformer() {
return AmdTransformer;
}};
});
System.register("traceur@0.0.52/src/staticsemantics/PropName", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/staticsemantics/PropName";
var $__255 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
COMPUTED_PROPERTY_NAME = $__255.COMPUTED_PROPERTY_NAME,
GET_ACCESSOR = $__255.GET_ACCESSOR,
LITERAL_PROPERTY_NAME = $__255.LITERAL_PROPERTY_NAME,
PROPERTY_METHOD_ASSIGNMENT = $__255.PROPERTY_METHOD_ASSIGNMENT,
PROPERTY_NAME_ASSIGNMENT = $__255.PROPERTY_NAME_ASSIGNMENT,
PROPERTY_NAME_SHORTHAND = $__255.PROPERTY_NAME_SHORTHAND,
SET_ACCESSOR = $__255.SET_ACCESSOR;
var IDENTIFIER = System.get("traceur@0.0.52/src/syntax/TokenType").IDENTIFIER;
function propName(tree) {
switch (tree.type) {
case LITERAL_PROPERTY_NAME:
var token = tree.literalToken;
if (token.isKeyword() || token.type === IDENTIFIER)
return token.toString();
return String(tree.literalToken.processedValue);
case COMPUTED_PROPERTY_NAME:
return '';
case PROPERTY_NAME_SHORTHAND:
return tree.name.toString();
case PROPERTY_METHOD_ASSIGNMENT:
case PROPERTY_NAME_ASSIGNMENT:
case GET_ACCESSOR:
case SET_ACCESSOR:
return propName(tree.name);
}
}
return {get propName() {
return propName;
}};
});
System.register("traceur@0.0.52/src/codegeneration/AnnotationsTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/AnnotationsTransformer";
var $__257 = Object.freeze(Object.defineProperties(["Object.getOwnPropertyDescriptor(", ")"], {raw: {value: Object.freeze(["Object.getOwnPropertyDescriptor(", ")"])}}));
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var CONSTRUCTOR = System.get("traceur@0.0.52/src/syntax/PredefinedName").CONSTRUCTOR;
var STRING = System.get("traceur@0.0.52/src/syntax/TokenType").STRING;
var $__261 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AnonBlock = $__261.AnonBlock,
ClassDeclaration = $__261.ClassDeclaration,
ExportDeclaration = $__261.ExportDeclaration,
FormalParameter = $__261.FormalParameter,
FunctionDeclaration = $__261.FunctionDeclaration,
GetAccessor = $__261.GetAccessor,
LiteralExpression = $__261.LiteralExpression,
PropertyMethodAssignment = $__261.PropertyMethodAssignment,
SetAccessor = $__261.SetAccessor;
var propName = System.get("traceur@0.0.52/src/staticsemantics/PropName").propName;
var $__263 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArgumentList = $__263.createArgumentList,
createArrayLiteralExpression = $__263.createArrayLiteralExpression,
createAssignmentStatement = $__263.createAssignmentStatement,
createIdentifierExpression = $__263.createIdentifierExpression,
createMemberExpression = $__263.createMemberExpression,
createNewExpression = $__263.createNewExpression,
createStringLiteralToken = $__263.createStringLiteralToken;
var parseExpression = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseExpression;
var AnnotationsScope = function AnnotationsScope() {
this.className = null;
this.isExport = false;
this.constructorParameters = [];
this.annotations = [];
this.metadata = [];
};
($traceurRuntime.createClass)(AnnotationsScope, {get inClassScope() {
return this.className !== null;
}}, {});
var AnnotationsTransformer = function AnnotationsTransformer() {
this.stack_ = [new AnnotationsScope()];
};
var $AnnotationsTransformer = AnnotationsTransformer;
($traceurRuntime.createClass)(AnnotationsTransformer, {
transformExportDeclaration: function(tree) {
var $__267;
var scope = this.pushAnnotationScope_();
scope.isExport = true;
($__267 = scope.annotations).push.apply($__267, $traceurRuntime.spread(tree.annotations));
var declaration = this.transformAny(tree.declaration);
if (declaration !== tree.declaration || tree.annotations.length > 0)
tree = new ExportDeclaration(tree.location, declaration, []);
return this.appendMetadata_(tree);
},
transformClassDeclaration: function(tree) {
var $__267,
$__268;
var elementsChanged = false;
var exportAnnotations = this.scope.isExport ? this.scope.annotations : [];
var scope = this.pushAnnotationScope_();
scope.className = tree.name;
($__267 = scope.annotations).push.apply($__267, $traceurRuntime.spread(exportAnnotations, tree.annotations));
tree = $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformClassDeclaration", [tree]);
($__268 = scope.metadata).unshift.apply($__268, $traceurRuntime.spread(this.transformMetadata_(createIdentifierExpression(tree.name), scope.annotations, scope.constructorParameters)));
if (tree.annotations.length > 0) {
tree = new ClassDeclaration(tree.location, tree.name, tree.superClass, tree.elements, []);
}
return this.appendMetadata_(tree);
},
transformFunctionDeclaration: function(tree) {
var $__267,
$__268;
var exportAnnotations = this.scope.isExport ? this.scope.annotations : [];
var scope = this.pushAnnotationScope_();
($__267 = scope.annotations).push.apply($__267, $traceurRuntime.spread(exportAnnotations, tree.annotations));
($__268 = scope.metadata).push.apply($__268, $traceurRuntime.spread(this.transformMetadata_(createIdentifierExpression(tree.name), scope.annotations, tree.parameterList.parameters)));
tree = $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformFunctionDeclaration", [tree]);
if (tree.annotations.length > 0) {
tree = new FunctionDeclaration(tree.location, tree.name, tree.functionKind, tree.parameterList, tree.typeAnnotation, [], tree.body);
}
return this.appendMetadata_(tree);
},
transformFormalParameter: function(tree) {
if (tree.annotations.length > 0) {
tree = new FormalParameter(tree.location, tree.parameter, tree.typeAnnotation, []);
}
return $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformFormalParameter", [tree]);
},
transformGetAccessor: function(tree) {
var $__267;
if (!this.scope.inClassScope)
return $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformGetAccessor", [tree]);
($__267 = this.scope.metadata).push.apply($__267, $traceurRuntime.spread(this.transformMetadata_(this.transformAccessor_(tree, this.scope.className, 'get'), tree.annotations, [])));
if (tree.annotations.length > 0) {
tree = new GetAccessor(tree.location, tree.isStatic, tree.name, tree.typeAnnotation, [], tree.body);
}
return $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformGetAccessor", [tree]);
},
transformSetAccessor: function(tree) {
var $__267;
if (!this.scope.inClassScope)
return $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformSetAccessor", [tree]);
($__267 = this.scope.metadata).push.apply($__267, $traceurRuntime.spread(this.transformMetadata_(this.transformAccessor_(tree, this.scope.className, 'set'), tree.annotations, tree.parameterList.parameters)));
var parameterList = this.transformAny(tree.parameterList);
if (parameterList !== tree.parameterList || tree.annotations.length > 0) {
tree = new SetAccessor(tree.location, tree.isStatic, tree.name, parameterList, [], tree.body);
}
return $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformSetAccessor", [tree]);
},
transformPropertyMethodAssignment: function(tree) {
var $__267,
$__268;
if (!this.scope.inClassScope)
return $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformPropertyMethodAssignment", [tree]);
if (!tree.isStatic && propName(tree) === CONSTRUCTOR) {
($__267 = this.scope.annotations).push.apply($__267, $traceurRuntime.spread(tree.annotations));
this.scope.constructorParameters = tree.parameterList.parameters;
} else {
($__268 = this.scope.metadata).push.apply($__268, $traceurRuntime.spread(this.transformMetadata_(this.transformPropertyMethod_(tree, this.scope.className), tree.annotations, tree.parameterList.parameters)));
}
var parameterList = this.transformAny(tree.parameterList);
if (parameterList !== tree.parameterList || tree.annotations.length > 0) {
tree = new PropertyMethodAssignment(tree.location, tree.isStatic, tree.functionKind, tree.name, parameterList, tree.typeAnnotation, [], tree.body);
}
return $traceurRuntime.superCall(this, $AnnotationsTransformer.prototype, "transformPropertyMethodAssignment", [tree]);
},
appendMetadata_: function(tree) {
var $__267;
var metadata = this.stack_.pop().metadata;
if (metadata.length > 0) {
if (this.scope.isExport) {
($__267 = this.scope.metadata).push.apply($__267, $traceurRuntime.spread(metadata));
} else {
tree = new AnonBlock(null, $traceurRuntime.spread([tree], metadata));
}
}
return tree;
},
transformClassReference_: function(tree, className) {
var parent = createIdentifierExpression(className);
if (!tree.isStatic)
parent = createMemberExpression(parent, 'prototype');
return parent;
},
transformPropertyMethod_: function(tree, className) {
return createMemberExpression(this.transformClassReference_(tree, className), tree.name.literalToken);
},
transformAccessor_: function(tree, className, accessor) {
var args = createArgumentList([this.transformClassReference_(tree, className), this.createLiteralStringExpression_(tree.name)]);
var descriptor = parseExpression($__257, args);
return createMemberExpression(descriptor, accessor);
},
transformParameters_: function(parameters) {
var $__265 = this;
var hasParameterMetadata = false;
parameters = parameters.map((function(param) {
var $__267;
var metadata = [];
if (param.typeAnnotation)
metadata.push($__265.transformAny(param.typeAnnotation));
if (param.annotations && param.annotations.length > 0)
($__267 = metadata).push.apply($__267, $traceurRuntime.spread($__265.transformAnnotations_(param.annotations)));
if (metadata.length > 0) {
hasParameterMetadata = true;
return createArrayLiteralExpression(metadata);
}
return createArrayLiteralExpression([]);
}));
return hasParameterMetadata ? parameters : [];
},
transformAnnotations_: function(annotations) {
return annotations.map((function(annotation) {
return createNewExpression(annotation.name, annotation.args);
}));
},
transformMetadata_: function(target, annotations, parameters) {
var metadataStatements = [];
if (annotations !== null) {
annotations = this.transformAnnotations_(annotations);
if (annotations.length > 0) {
metadataStatements.push(createAssignmentStatement(createMemberExpression(target, 'annotations'), createArrayLiteralExpression(annotations)));
}
}
if (parameters !== null) {
parameters = this.transformParameters_(parameters);
if (parameters.length > 0) {
metadataStatements.push(createAssignmentStatement(createMemberExpression(target, 'parameters'), createArrayLiteralExpression(parameters)));
}
}
return metadataStatements;
},
createLiteralStringExpression_: function(tree) {
var token = tree.literalToken;
if (tree.literalToken.type !== STRING)
token = createStringLiteralToken(tree.literalToken.value);
return new LiteralExpression(null, token);
},
get scope() {
return this.stack_[this.stack_.length - 1];
},
pushAnnotationScope_: function() {
var scope = new AnnotationsScope();
this.stack_.push(scope);
return scope;
}
}, {}, ParseTreeTransformer);
return {get AnnotationsTransformer() {
return AnnotationsTransformer;
}};
});
System.register("traceur@0.0.52/src/semantics/VariableBinder", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/semantics/VariableBinder";
var ScopeChainBuilder = System.get("traceur@0.0.52/src/semantics/ScopeChainBuilder").ScopeChainBuilder;
function variablesInBlock(tree) {
var includeFunctionScope = arguments[1];
var builder = new ScopeChainBuilder(null);
builder.visitAny(tree);
var scope = builder.getScopeForTree(tree);
var names = scope.getLexicalBindingNames();
if (!includeFunctionScope) {
return names;
}
var variableBindingNames = scope.getVariableBindingNames();
for (var name in variableBindingNames) {
names[name] = true;
}
return names;
}
function variablesInFunction(tree) {
var builder = new ScopeChainBuilder(null);
builder.visitAny(tree);
var scope = builder.getScopeForTree(tree);
return scope.getVariableBindingNames();
}
return {
get variablesInBlock() {
return variablesInBlock;
},
get variablesInFunction() {
return variablesInFunction;
}
};
});
System.register("traceur@0.0.52/src/codegeneration/ScopeTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ScopeTransformer";
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__271 = System.get("traceur@0.0.52/src/syntax/PredefinedName"),
ARGUMENTS = $__271.ARGUMENTS,
THIS = $__271.THIS;
var $__272 = System.get("traceur@0.0.52/src/semantics/VariableBinder"),
variablesInBlock = $__272.variablesInBlock,
variablesInFunction = $__272.variablesInFunction;
var ScopeTransformer = function ScopeTransformer(varName) {
$traceurRuntime.superCall(this, $ScopeTransformer.prototype, "constructor", []);
this.varName_ = varName;
};
var $ScopeTransformer = ScopeTransformer;
($traceurRuntime.createClass)(ScopeTransformer, {
transformBlock: function(tree) {
if (this.varName_ in variablesInBlock(tree)) {
return tree;
} else {
return $traceurRuntime.superCall(this, $ScopeTransformer.prototype, "transformBlock", [tree]);
}
},
transformThisExpression: function(tree) {
if (this.varName_ !== THIS)
return tree;
return $traceurRuntime.superCall(this, $ScopeTransformer.prototype, "transformThisExpression", [tree]);
},
transformFunctionDeclaration: function(tree) {
if (this.getDoNotRecurse(tree))
return tree;
return $traceurRuntime.superCall(this, $ScopeTransformer.prototype, "transformFunctionDeclaration", [tree]);
},
transformFunctionExpression: function(tree) {
if (this.getDoNotRecurse(tree))
return tree;
return $traceurRuntime.superCall(this, $ScopeTransformer.prototype, "transformFunctionExpression", [tree]);
},
getDoNotRecurse: function(tree) {
return this.varName_ === ARGUMENTS || this.varName_ === THIS || this.varName_ in variablesInFunction(tree);
},
transformCatch: function(tree) {
if (!tree.binding.isPattern() && this.varName_ === tree.binding.identifierToken.value) {
return tree;
}
return $traceurRuntime.superCall(this, $ScopeTransformer.prototype, "transformCatch", [tree]);
}
}, {}, ParseTreeTransformer);
return {get ScopeTransformer() {
return ScopeTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/AlphaRenamer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/AlphaRenamer";
var ScopeTransformer = System.get("traceur@0.0.52/src/codegeneration/ScopeTransformer").ScopeTransformer;
var $__275 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
FunctionDeclaration = $__275.FunctionDeclaration,
FunctionExpression = $__275.FunctionExpression;
var THIS = System.get("traceur@0.0.52/src/syntax/PredefinedName").THIS;
var createIdentifierExpression = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createIdentifierExpression;
var AlphaRenamer = function AlphaRenamer(varName, newName) {
$traceurRuntime.superCall(this, $AlphaRenamer.prototype, "constructor", [varName]);
this.newName_ = newName;
};
var $AlphaRenamer = AlphaRenamer;
($traceurRuntime.createClass)(AlphaRenamer, {
transformIdentifierExpression: function(tree) {
if (this.varName_ == tree.identifierToken.value) {
return createIdentifierExpression(this.newName_);
} else {
return tree;
}
},
transformThisExpression: function(tree) {
if (this.varName_ !== THIS)
return tree;
return createIdentifierExpression(this.newName_);
},
transformFunctionDeclaration: function(tree) {
if (this.varName_ === tree.name) {
tree = new FunctionDeclaration(tree.location, this.newName_, tree.functionKind, tree.parameterList, tree.typeAnnotation, tree.annotations, tree.body);
}
return $traceurRuntime.superCall(this, $AlphaRenamer.prototype, "transformFunctionDeclaration", [tree]);
},
transformFunctionExpression: function(tree) {
if (this.varName_ === tree.name) {
tree = new FunctionExpression(tree.location, this.newName_, tree.functionKind, tree.parameterList, tree.typeAnnotation, tree.annotations, tree.body);
}
return $traceurRuntime.superCall(this, $AlphaRenamer.prototype, "transformFunctionExpression", [tree]);
}
}, {rename: function(tree, varName, newName) {
return new $AlphaRenamer(varName, newName).transformAny(tree);
}}, ScopeTransformer);
return {get AlphaRenamer() {
return AlphaRenamer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/alphaRenameThisAndArguments", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/alphaRenameThisAndArguments";
var $__279 = System.get("traceur@0.0.52/src/syntax/PredefinedName"),
ARGUMENTS = $__279.ARGUMENTS,
THIS = $__279.THIS;
var AlphaRenamer = System.get("traceur@0.0.52/src/codegeneration/AlphaRenamer").AlphaRenamer;
var FindInFunctionScope = System.get("traceur@0.0.52/src/codegeneration/FindInFunctionScope").FindInFunctionScope;
var FindThisOrArguments = function FindThisOrArguments(tree) {
this.foundThis = false;
this.foundArguments = false;
$traceurRuntime.superCall(this, $FindThisOrArguments.prototype, "constructor", [tree]);
};
var $FindThisOrArguments = FindThisOrArguments;
($traceurRuntime.createClass)(FindThisOrArguments, {
visitThisExpression: function(tree) {
this.foundThis = true;
this.found = this.foundArguments;
},
visitIdentifierExpression: function(tree) {
if (tree.identifierToken.value === ARGUMENTS) {
this.foundArguments = true;
this.found = this.foundThis;
}
}
}, {}, FindInFunctionScope);
function alphaRenameThisAndArguments(tempVarTransformer, tree) {
var finder = new FindThisOrArguments(tree);
if (finder.foundArguments) {
var argumentsTempName = tempVarTransformer.addTempVarForArguments();
tree = AlphaRenamer.rename(tree, ARGUMENTS, argumentsTempName);
}
if (finder.foundThis) {
var thisTempName = tempVarTransformer.addTempVarForThis();
tree = AlphaRenamer.rename(tree, THIS, thisTempName);
}
return tree;
}
var $__default = alphaRenameThisAndArguments;
return {get default() {
return $__default;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ComprehensionTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ComprehensionTransformer";
var alphaRenameThisAndArguments = System.get("traceur@0.0.52/src/codegeneration/alphaRenameThisAndArguments").default;
var FunctionExpression = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").FunctionExpression;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__286 = System.get("traceur@0.0.52/src/syntax/TokenType"),
LET = $__286.LET,
STAR = $__286.STAR,
VAR = $__286.VAR;
var $__287 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
COMPREHENSION_FOR = $__287.COMPREHENSION_FOR,
COMPREHENSION_IF = $__287.COMPREHENSION_IF;
var Token = System.get("traceur@0.0.52/src/syntax/Token").Token;
var $__289 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createCallExpression = $__289.createCallExpression,
createEmptyParameterList = $__289.createEmptyParameterList,
createForOfStatement = $__289.createForOfStatement,
createFunctionBody = $__289.createFunctionBody,
createIfStatement = $__289.createIfStatement,
createParenExpression = $__289.createParenExpression,
createVariableDeclarationList = $__289.createVariableDeclarationList;
var options = System.get("traceur@0.0.52/src/Options").options;
var ComprehensionTransformer = function ComprehensionTransformer() {
$traceurRuntime.defaultSuperCall(this, $ComprehensionTransformer.prototype, arguments);
};
var $ComprehensionTransformer = ComprehensionTransformer;
($traceurRuntime.createClass)(ComprehensionTransformer, {transformComprehension: function(tree, statement, isGenerator) {
var prefix = arguments[3];
var suffix = arguments[4];
var bindingKind = isGenerator || !options.blockBinding ? VAR : LET;
var statements = prefix ? [prefix] : [];
for (var i = tree.comprehensionList.length - 1; i >= 0; i--) {
var item = tree.comprehensionList[i];
switch (item.type) {
case COMPREHENSION_IF:
var expression = this.transformAny(item.expression);
statement = createIfStatement(expression, statement);
break;
case COMPREHENSION_FOR:
var left = this.transformAny(item.left);
var iterator = this.transformAny(item.iterator);
var initializer = createVariableDeclarationList(bindingKind, left, null);
statement = createForOfStatement(initializer, iterator, statement);
break;
default:
throw new Error('Unreachable.');
}
}
statement = alphaRenameThisAndArguments(this, statement);
statements.push(statement);
if (suffix)
statements.push(suffix);
var functionKind = isGenerator ? new Token(STAR, null) : null;
var func = new FunctionExpression(null, null, functionKind, createEmptyParameterList(), null, [], createFunctionBody(statements));
return createParenExpression(createCallExpression(func));
}}, {}, TempVarTransformer);
return {get ComprehensionTransformer() {
return ComprehensionTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ArrayComprehensionTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ArrayComprehensionTransformer";
var $__292 = Object.freeze(Object.defineProperties(["var ", " = 0, ", " = [];"], {raw: {value: Object.freeze(["var ", " = 0, ", " = [];"])}})),
$__293 = Object.freeze(Object.defineProperties(["", "[", "++] = ", ";"], {raw: {value: Object.freeze(["", "[", "++] = ", ";"])}})),
$__294 = Object.freeze(Object.defineProperties(["return ", ";"], {raw: {value: Object.freeze(["return ", ";"])}}));
var ComprehensionTransformer = System.get("traceur@0.0.52/src/codegeneration/ComprehensionTransformer").ComprehensionTransformer;
var createIdentifierExpression = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createIdentifierExpression;
var parseStatement = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatement;
var ArrayComprehensionTransformer = function ArrayComprehensionTransformer() {
$traceurRuntime.defaultSuperCall(this, $ArrayComprehensionTransformer.prototype, arguments);
};
var $ArrayComprehensionTransformer = ArrayComprehensionTransformer;
($traceurRuntime.createClass)(ArrayComprehensionTransformer, {transformArrayComprehension: function(tree) {
this.pushTempScope();
var expression = this.transformAny(tree.expression);
var index = createIdentifierExpression(this.getTempIdentifier());
var result = createIdentifierExpression(this.getTempIdentifier());
var tempVarsStatatement = parseStatement($__292, index, result);
var statement = parseStatement($__293, result, index, expression);
var returnStatement = parseStatement($__294, result);
var functionKind = null;
var result = this.transformComprehension(tree, statement, functionKind, tempVarsStatatement, returnStatement);
this.popTempScope();
return result;
}}, {}, ComprehensionTransformer);
return {get ArrayComprehensionTransformer() {
return ArrayComprehensionTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ArrowFunctionTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ArrowFunctionTransformer";
var FunctionExpression = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").FunctionExpression;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var FUNCTION_BODY = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType").FUNCTION_BODY;
var alphaRenameThisAndArguments = System.get("traceur@0.0.52/src/codegeneration/alphaRenameThisAndArguments").default;
var $__303 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createFunctionBody = $__303.createFunctionBody,
createParenExpression = $__303.createParenExpression,
createReturnStatement = $__303.createReturnStatement;
function convertConciseBody(tree) {
if (tree.type !== FUNCTION_BODY)
return createFunctionBody([createReturnStatement(tree)]);
return tree;
}
var ArrowFunctionTransformer = function ArrowFunctionTransformer() {
$traceurRuntime.defaultSuperCall(this, $ArrowFunctionTransformer.prototype, arguments);
};
var $ArrowFunctionTransformer = ArrowFunctionTransformer;
($traceurRuntime.createClass)(ArrowFunctionTransformer, {transformArrowFunctionExpression: function(tree) {
var alphaRenamed = alphaRenameThisAndArguments(this, tree);
var parameterList = this.transformAny(alphaRenamed.parameterList);
var body = this.transformAny(alphaRenamed.body);
body = convertConciseBody(body);
var functionExpression = new FunctionExpression(tree.location, null, tree.functionKind, parameterList, null, [], body);
return createParenExpression(functionExpression);
}}, {transform: function(tempVarTransformer, tree) {
tree = alphaRenameThisAndArguments(tempVarTransformer, tree);
var body = convertConciseBody(tree.body);
return new FunctionExpression(tree.location, null, tree.functionKind, tree.parameterList, null, [], body);
}}, TempVarTransformer);
return {get ArrowFunctionTransformer() {
return ArrowFunctionTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/BlockBindingTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/BlockBindingTransformer";
var AlphaRenamer = System.get("traceur@0.0.52/src/codegeneration/AlphaRenamer").AlphaRenamer;
var $__306 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BINDING_IDENTIFIER = $__306.BINDING_IDENTIFIER,
BLOCK = $__306.BLOCK,
VARIABLE_DECLARATION_LIST = $__306.VARIABLE_DECLARATION_LIST;
var $__307 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
FunctionDeclaration = $__307.FunctionDeclaration,
FunctionExpression = $__307.FunctionExpression;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__309 = System.get("traceur@0.0.52/src/syntax/TokenType"),
CONST = $__309.CONST,
LET = $__309.LET,
VAR = $__309.VAR;
var $__310 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createAssignmentExpression = $__310.createAssignmentExpression,
createBindingIdentifier = $__310.createBindingIdentifier,
createBlock = $__310.createBlock,
createCatch = $__310.createCatch,
createEmptyStatement = $__310.createEmptyStatement,
createExpressionStatement = $__310.createExpressionStatement,
createFinally = $__310.createFinally,
createForInStatement = $__310.createForInStatement,
createForStatement = $__310.createForStatement,
createFunctionBody = $__310.createFunctionBody,
createIdentifierExpression = $__310.createIdentifierExpression,
createIdentifierToken = $__310.createIdentifierToken,
createThrowStatement = $__310.createThrowStatement,
createTryStatement = $__310.createTryStatement,
createUndefinedExpression = $__310.createUndefinedExpression,
createVariableDeclaration = $__310.createVariableDeclaration,
createVariableDeclarationList = $__310.createVariableDeclarationList,
createVariableStatement = $__310.createVariableStatement;
var ScopeType = {
SCRIPT: 'SCRIPT',
FUNCTION: 'FUNCTION',
BLOCK: 'BLOCK'
};
var Scope = function Scope(parent, type) {
this.parent = parent;
this.type = type;
this.blockVariables = null;
};
($traceurRuntime.createClass)(Scope, {addBlockScopedVariable: function(value) {
if (!this.blockVariables) {
this.blockVariables = Object.create(null);
}
this.blockVariables[value] = true;
}}, {});
;
var Rename = function Rename(oldName, newName) {
this.oldName = oldName;
this.newName = newName;
};
($traceurRuntime.createClass)(Rename, {}, {});
function renameAll(renames, tree) {
renames.forEach((function(rename) {
tree = AlphaRenamer.rename(tree, rename.oldName, rename.newName);
}));
return tree;
}
function toBlock(statement) {
return statement.type == BLOCK ? statement : createBlock([statement]);
}
var BlockBindingTransformer = function BlockBindingTransformer(stateAllocator) {
$traceurRuntime.superCall(this, $BlockBindingTransformer.prototype, "constructor", []);
this.scope_ = null;
};
var $BlockBindingTransformer = BlockBindingTransformer;
($traceurRuntime.createClass)(BlockBindingTransformer, {
createScriptScope_: function() {
return new Scope(this.scope_, ScopeType.SCRIPT);
},
createFunctionScope_: function() {
if (this.scope_ == null) {
throw new Error('Top level function scope found.');
}
return new Scope(this.scope_, ScopeType.FUNCTION);
},
createBlockScope_: function() {
if (this.scope_ == null) {
throw new Error('Top level block scope found.');
}
return new Scope(this.scope_, ScopeType.BLOCK);
},
push_: function(scope) {
this.scope_ = scope;
return scope;
},
pop_: function(scope) {
if (this.scope_ != scope) {
throw new Error('BlockBindingTransformer scope mismatch');
}
this.scope_ = scope.parent;
},
transformBlock: function(tree) {
var scope = this.push_(this.createBlockScope_());
var statements = this.transformList(tree.statements);
if (scope.blockVariables != null) {
tree = createBlock([this.rewriteAsCatch_(scope.blockVariables, createBlock(statements))]);
} else if (statements != tree.statements) {
tree = createBlock(statements);
}
this.pop_(scope);
return tree;
},
rewriteAsCatch_: function(blockVariables, statement) {
for (var variable in blockVariables) {
statement = createTryStatement(createBlock([createThrowStatement(createUndefinedExpression())]), createCatch(createBindingIdentifier(variable), createBlock([statement])), null);
}
return statement;
},
transformClassDeclaration: function(tree) {
throw new Error('ClassDeclaration should be transformed away.');
},
transformForInStatement: function(tree) {
var treeBody = tree.body;
var initializer;
if (tree.initializer != null && tree.initializer.type == VARIABLE_DECLARATION_LIST) {
var variables = tree.initializer;
if (variables.declarations.length != 1) {
throw new Error('for .. in has != 1 variables');
}
var variable = variables.declarations[0];
var variableName = this.getVariableName_(variable);
switch (variables.declarationType) {
case LET:
case CONST:
{
if (variable.initializer != null) {
throw new Error('const/let in for-in may not have an initializer');
}
initializer = createVariableDeclarationList(VAR, ("$" + variableName), null);
treeBody = this.prependToBlock_(createVariableStatement(LET, variableName, createIdentifierExpression(("$" + variableName))), treeBody);
break;
}
case VAR:
initializer = this.transformVariables_(variables);
break;
default:
throw new Error('Unreachable.');
}
} else {
initializer = this.transformAny(tree.initializer);
}
var result = tree;
var collection = this.transformAny(tree.collection);
var body = this.transformAny(treeBody);
if (initializer != tree.initializer || collection != tree.collection || body != tree.body) {
result = createForInStatement(initializer, collection, body);
}
return result;
},
prependToBlock_: function(statement, body) {
if (body.type == BLOCK) {
return createBlock($traceurRuntime.spread([statement], body.statements));
} else {
return createBlock([statement, body]);
}
},
transformForStatement: function(tree) {
var initializer;
if (tree.initializer != null && tree.initializer.type == VARIABLE_DECLARATION_LIST) {
var variables = tree.initializer;
switch (variables.declarationType) {
case LET:
case CONST:
return this.transformForLet_(tree, variables);
case VAR:
initializer = this.transformVariables_(variables);
break;
default:
throw new Error('Reached unreachable.');
}
} else {
initializer = this.transformAny(tree.initializer);
}
var condition = this.transformAny(tree.condition);
var increment = this.transformAny(tree.increment);
var body = this.transformAny(tree.body);
var result = tree;
if (initializer != tree.initializer || condition != tree.condition || increment != tree.increment || body != tree.body) {
result = createForStatement(initializer, condition, increment, body);
}
return result;
},
transformForLet_: function(tree, variables) {
var $__311 = this;
var copyFwd = [];
var copyBak = [];
var hoisted = [];
var renames = [];
variables.declarations.forEach((function(variable) {
var variableName = $__311.getVariableName_(variable);
var hoistedName = ("$" + variableName);
var initializer = renameAll(renames, variable.initializer);
hoisted.push(createVariableDeclaration(hoistedName, initializer));
copyFwd.push(createVariableDeclaration(variableName, createIdentifierExpression(hoistedName)));
copyBak.push(createExpressionStatement(createAssignmentExpression(createIdentifierExpression(hoistedName), createIdentifierExpression(variableName))));
renames.push(new Rename(variableName, hoistedName));
}));
var condition = renameAll(renames, tree.condition);
var increment = renameAll(renames, tree.increment);
var transformedForLoop = createBlock([createVariableStatement(createVariableDeclarationList(LET, hoisted)), createForStatement(null, condition, increment, createBlock([createVariableStatement(createVariableDeclarationList(LET, copyFwd)), createTryStatement(toBlock(tree.body), null, createFinally(createBlock(copyBak)))]))]);
return this.transformAny(transformedForLoop);
},
transformFunctionDeclaration: function(tree) {
var body = this.transformFunctionBody(tree.body);
var parameterList = this.transformAny(tree.parameterList);
if (this.scope_.type === ScopeType.BLOCK) {
this.scope_.addBlockScopedVariable(tree.name.identifierToken.value);
return createExpressionStatement(createAssignmentExpression(createIdentifierExpression(tree.name.identifierToken), new FunctionExpression(tree.location, null, tree.functionKind, parameterList, tree.typeAnnotation, tree.annotations, body)));
}
if (body === tree.body && parameterList === tree.parameterList) {
return tree;
}
return new FunctionDeclaration(tree.location, tree.name, tree.functionKind, parameterList, tree.typeAnnotation, tree.annotations, body);
},
transformScript: function(tree) {
var scope = this.push_(this.createScriptScope_());
var result = $traceurRuntime.superCall(this, $BlockBindingTransformer.prototype, "transformScript", [tree]);
this.pop_(scope);
return result;
},
transformVariableDeclaration: function(tree) {
throw new Error('Should never see variable declaration tree.');
},
transformVariableDeclarationList: function(tree) {
throw new Error('Should never see variable declaration list.');
},
transformVariableStatement: function(tree) {
if (this.scope_.type == ScopeType.BLOCK) {
switch (tree.declarations.declarationType) {
case CONST:
case LET:
return this.transformBlockVariables_(tree.declarations);
default:
break;
}
}
var variables = this.transformVariables_(tree.declarations);
if (variables != tree.declarations) {
tree = createVariableStatement(variables);
}
return tree;
},
transformBlockVariables_: function(tree) {
var $__311 = this;
var variables = tree.declarations;
var commaExpressions = [];
variables.forEach((function(variable) {
switch (tree.declarationType) {
case LET:
case CONST:
break;
default:
throw new Error('Only let/const allowed here.');
}
var variableName = $__311.getVariableName_(variable);
$__311.scope_.addBlockScopedVariable(variableName);
var initializer = $__311.transformAny(variable.initializer);
if (initializer != null) {
commaExpressions.push(createAssignmentExpression(createIdentifierExpression(variableName), initializer));
}
}));
switch (commaExpressions.length) {
case 0:
return createEmptyStatement();
case 1:
return createExpressionStatement(commaExpressions[0]);
default:
for (var i = 0; i < commaExpressions.length; i++) {
commaExpressions[i] = createExpressionStatement(commaExpressions[i]);
}
return createBlock(commaExpressions);
}
},
transformVariables_: function(tree) {
var variables = tree.declarations;
var transformed = null;
for (var index = 0; index < variables.length; index++) {
var variable = variables[index];
var variableName = this.getVariableName_(variable);
var initializer = this.transformAny(variable.initializer);
if (transformed != null || initializer != variable.initializer) {
if (transformed == null) {
transformed = variables.slice(0, index);
}
transformed.push(createVariableDeclaration(createIdentifierToken(variableName), initializer));
}
}
if (transformed != null || tree.declarationType != VAR) {
var declarations = transformed != null ? transformed : tree.declarations;
var declarationType = tree.declarationType != VAR ? VAR : tree.declarationType;
tree = createVariableDeclarationList(declarationType, declarations);
}
return tree;
},
transformFunctionBody: function(body) {
var scope = this.push_(this.createFunctionScope_());
body = this.transformFunctionBodyStatements_(body);
this.pop_(scope);
return body;
},
transformFunctionBodyStatements_: function(tree) {
var statements = this.transformList(tree.statements);
if (this.scope_.blockVariables != null) {
tree = this.rewriteAsCatch_(this.scope_.blockVariables, createBlock(statements));
} else if (statements != tree.statements) {
tree = createFunctionBody(statements);
}
return tree;
},
getVariableName_: function(variable) {
var lvalue = variable.lvalue;
if (lvalue.type == BINDING_IDENTIFIER) {
return lvalue.identifierToken.value;
}
throw new Error('Unexpected destructuring declaration found.');
}
}, {}, ParseTreeTransformer);
return {get BlockBindingTransformer() {
return BlockBindingTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/MakeStrictTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/MakeStrictTransformer";
var $__313 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
FunctionBody = $__313.FunctionBody,
Script = $__313.Script;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var createUseStrictDirective = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createUseStrictDirective;
var hasUseStrict = System.get("traceur@0.0.52/src/semantics/util").hasUseStrict;
function prepend(statements) {
return $traceurRuntime.spread([createUseStrictDirective()], statements);
}
var MakeStrictTransformer = function MakeStrictTransformer() {
$traceurRuntime.defaultSuperCall(this, $MakeStrictTransformer.prototype, arguments);
};
var $MakeStrictTransformer = MakeStrictTransformer;
($traceurRuntime.createClass)(MakeStrictTransformer, {
transformScript: function(tree) {
if (hasUseStrict(tree.scriptItemList))
return tree;
return new Script(tree.location, prepend(tree.scriptItemList));
},
transformFunctionBody: function(tree) {
if (hasUseStrict(tree.statements))
return tree;
return new FunctionBody(tree.location, prepend(tree.statements));
}
}, {transformTree: function(tree) {
return new $MakeStrictTransformer().transformAny(tree);
}}, ParseTreeTransformer);
return {get MakeStrictTransformer() {
return MakeStrictTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/assignmentOperatorToBinaryOperator", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/assignmentOperatorToBinaryOperator";
var $__318 = System.get("traceur@0.0.52/src/syntax/TokenType"),
AMPERSAND = $__318.AMPERSAND,
AMPERSAND_EQUAL = $__318.AMPERSAND_EQUAL,
BAR = $__318.BAR,
BAR_EQUAL = $__318.BAR_EQUAL,
CARET = $__318.CARET,
CARET_EQUAL = $__318.CARET_EQUAL,
LEFT_SHIFT = $__318.LEFT_SHIFT,
LEFT_SHIFT_EQUAL = $__318.LEFT_SHIFT_EQUAL,
MINUS = $__318.MINUS,
MINUS_EQUAL = $__318.MINUS_EQUAL,
PERCENT = $__318.PERCENT,
PERCENT_EQUAL = $__318.PERCENT_EQUAL,
PLUS = $__318.PLUS,
PLUS_EQUAL = $__318.PLUS_EQUAL,
RIGHT_SHIFT = $__318.RIGHT_SHIFT,
RIGHT_SHIFT_EQUAL = $__318.RIGHT_SHIFT_EQUAL,
SLASH = $__318.SLASH,
SLASH_EQUAL = $__318.SLASH_EQUAL,
STAR = $__318.STAR,
STAR_EQUAL = $__318.STAR_EQUAL,
UNSIGNED_RIGHT_SHIFT = $__318.UNSIGNED_RIGHT_SHIFT,
UNSIGNED_RIGHT_SHIFT_EQUAL = $__318.UNSIGNED_RIGHT_SHIFT_EQUAL;
function assignmentOperatorToBinaryOperator(type) {
switch (type) {
case STAR_EQUAL:
return STAR;
case SLASH_EQUAL:
return SLASH;
case PERCENT_EQUAL:
return PERCENT;
case PLUS_EQUAL:
return PLUS;
case MINUS_EQUAL:
return MINUS;
case LEFT_SHIFT_EQUAL:
return LEFT_SHIFT;
case RIGHT_SHIFT_EQUAL:
return RIGHT_SHIFT;
case UNSIGNED_RIGHT_SHIFT_EQUAL:
return UNSIGNED_RIGHT_SHIFT;
case AMPERSAND_EQUAL:
return AMPERSAND;
case CARET_EQUAL:
return CARET;
case BAR_EQUAL:
return BAR;
default:
throw Error('unreachable');
}
}
var $__default = assignmentOperatorToBinaryOperator;
return {get default() {
return $__default;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ExplodeExpressionTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ExplodeExpressionTransformer";
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__320 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createAssignmentExpression = $__320.createAssignmentExpression,
createCommaExpression = $__320.createCommaExpression,
id = $__320.createIdentifierExpression,
createMemberExpression = $__320.createMemberExpression,
createNumberLiteral = $__320.createNumberLiteral,
createOperatorToken = $__320.createOperatorToken,
createParenExpression = $__320.createParenExpression;
var $__321 = System.get("traceur@0.0.52/src/syntax/TokenType"),
AND = $__321.AND,
EQUAL = $__321.EQUAL,
MINUS = $__321.MINUS,
MINUS_EQUAL = $__321.MINUS_EQUAL,
MINUS_MINUS = $__321.MINUS_MINUS,
OR = $__321.OR,
PLUS = $__321.PLUS,
PLUS_EQUAL = $__321.PLUS_EQUAL,
PLUS_PLUS = $__321.PLUS_PLUS;
var $__322 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
COMMA_EXPRESSION = $__322.COMMA_EXPRESSION,
IDENTIFIER_EXPRESSION = $__322.IDENTIFIER_EXPRESSION,
MEMBER_EXPRESSION = $__322.MEMBER_EXPRESSION,
MEMBER_LOOKUP_EXPRESSION = $__322.MEMBER_LOOKUP_EXPRESSION,
PROPERTY_NAME_ASSIGNMENT = $__322.PROPERTY_NAME_ASSIGNMENT,
SPREAD_EXPRESSION = $__322.SPREAD_EXPRESSION,
TEMPLATE_LITERAL_PORTION = $__322.TEMPLATE_LITERAL_PORTION;
var $__323 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
ArgumentList = $__323.ArgumentList,
ArrayLiteralExpression = $__323.ArrayLiteralExpression,
AwaitExpression = $__323.AwaitExpression,
BinaryExpression = $__323.BinaryExpression,
CallExpression = $__323.CallExpression,
ConditionalExpression = $__323.ConditionalExpression,
MemberExpression = $__323.MemberExpression,
MemberLookupExpression = $__323.MemberLookupExpression,
NewExpression = $__323.NewExpression,
ObjectLiteralExpression = $__323.ObjectLiteralExpression,
PropertyNameAssignment = $__323.PropertyNameAssignment,
SpreadExpression = $__323.SpreadExpression,
TemplateLiteralExpression = $__323.TemplateLiteralExpression,
TemplateSubstitution = $__323.TemplateSubstitution,
UnaryExpression = $__323.UnaryExpression,
YieldExpression = $__323.YieldExpression;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var assignmentOperatorToBinaryOperator = System.get("traceur@0.0.52/src/codegeneration/assignmentOperatorToBinaryOperator").default;
var CommaExpressionBuilder = function CommaExpressionBuilder(tempVar) {
this.tempVar = tempVar;
this.expressions = [];
};
($traceurRuntime.createClass)(CommaExpressionBuilder, {
add: function(tree) {
var $__327;
if (tree.type === COMMA_EXPRESSION)
($__327 = this.expressions).push.apply($__327, $traceurRuntime.spread(getExpressions(tree)));
return this;
},
build: function(tree) {
var tempVar = this.tempVar;
this.expressions.push(createAssignmentExpression(tempVar, tree), tempVar);
return createCommaExpression(this.expressions);
}
}, {});
function getResult(tree) {
if (tree.type === COMMA_EXPRESSION)
return tree.expressions[tree.expressions.length - 1];
return tree;
}
function getExpressions(tree) {
if (tree.type === COMMA_EXPRESSION)
return tree.expressions.slice(0, -1);
return [];
}
var ExplodeExpressionTransformer = function ExplodeExpressionTransformer(tempVarTransformer) {
$traceurRuntime.superCall(this, $ExplodeExpressionTransformer.prototype, "constructor", []);
this.tempVarTransformer_ = tempVarTransformer;
};
var $ExplodeExpressionTransformer = ExplodeExpressionTransformer;
($traceurRuntime.createClass)(ExplodeExpressionTransformer, {
addTempVar: function() {
var tmpId = this.tempVarTransformer_.addTempVar();
return id(tmpId);
},
transformUnaryExpression: function(tree) {
if (tree.operator.type == PLUS_PLUS)
return this.transformUnaryNumeric(tree, PLUS_EQUAL);
if (tree.operator.type == MINUS_MINUS)
return this.transformUnaryNumeric(tree, MINUS_EQUAL);
var operand = this.transformAny(tree.operand);
if (operand === tree.operand)
return tree;
var expressions = $traceurRuntime.spread(getExpressions(operand), [new UnaryExpression(tree.location, tree.operator, getResult(operand))]);
return createCommaExpression(expressions);
},
transformUnaryNumeric: function(tree, operator) {
return this.transformAny(new BinaryExpression(tree.location, tree.operand, createOperatorToken(operator), createNumberLiteral(1)));
},
transformPostfixExpression: function(tree) {
if (tree.operand.type === MEMBER_EXPRESSION)
return this.transformPostfixMemberExpression(tree);
if (tree.operand.type === MEMBER_LOOKUP_EXPRESSION)
return this.transformPostfixMemberLookupExpression(tree);
assert(tree.operand.type === IDENTIFIER_EXPRESSION);
var operand = tree.operand;
var tmp = this.addTempVar();
var operator = tree.operator.type === PLUS_PLUS ? PLUS : MINUS;
var expressions = [createAssignmentExpression(tmp, operand), createAssignmentExpression(operand, new BinaryExpression(tree.location, tmp, createOperatorToken(operator), createNumberLiteral(1))), tmp];
return createCommaExpression(expressions);
},
transformPostfixMemberExpression: function(tree) {
var memberName = tree.operand.memberName;
var operand = this.transformAny(tree.operand.operand);
var tmp = this.addTempVar();
var memberExpression = new MemberExpression(tree.operand.location, getResult(operand), memberName);
var operator = tree.operator.type === PLUS_PLUS ? PLUS : MINUS;
var expressions = $traceurRuntime.spread(getExpressions(operand), [createAssignmentExpression(tmp, memberExpression), createAssignmentExpression(memberExpression, new BinaryExpression(tree.location, tmp, createOperatorToken(operator), createNumberLiteral(1))), tmp]);
return createCommaExpression(expressions);
},
transformPostfixMemberLookupExpression: function(tree) {
var memberExpression = this.transformAny(tree.operand.memberExpression);
var operand = this.transformAny(tree.operand.operand);
var tmp = this.addTempVar();
var memberLookupExpression = new MemberLookupExpression(null, getResult(operand), getResult(memberExpression));
var operator = tree.operator.type === PLUS_PLUS ? PLUS : MINUS;
var expressions = $traceurRuntime.spread(getExpressions(operand), getExpressions(memberExpression), [createAssignmentExpression(tmp, memberLookupExpression), createAssignmentExpression(memberLookupExpression, new BinaryExpression(tree.location, tmp, createOperatorToken(operator), createNumberLiteral(1))), tmp]);
return createCommaExpression(expressions);
},
transformYieldExpression: function(tree) {
var expression = this.transformAny(tree.expression);
return this.createCommaExpressionBuilder().add(expression).build(new YieldExpression(tree.location, getResult(expression), tree.isYieldFor));
},
transformAwaitExpression: function(tree) {
var expression = this.transformAny(tree.expression);
return this.createCommaExpressionBuilder().add(expression).build(new AwaitExpression(tree.location, getResult(expression)));
},
transformParenExpression: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression)
return tree;
var result = getResult(expression);
if (result.type === IDENTIFIER_EXPRESSION)
return expression;
return this.createCommaExpressionBuilder().add(expression).build(result);
},
transformCommaExpression: function(tree) {
var expressions = this.transformList(tree.expressions);
if (expressions === tree.expressions)
return tree;
var builder = new CommaExpressionBuilder(null);
for (var i = 0; i < expressions.length; i++) {
builder.add(expressions[i]);
}
return createCommaExpression($traceurRuntime.spread(builder.expressions, [getResult(expressions[expressions.length - 1])]));
},
transformMemberExpression: function(tree) {
var operand = this.transformAny(tree.operand);
return this.createCommaExpressionBuilder().add(operand).build(new MemberExpression(tree.location, getResult(operand), tree.memberName));
},
transformMemberLookupExpression: function(tree) {
var operand = this.transformAny(tree.operand);
var memberExpression = this.transformAny(tree.memberExpression);
return this.createCommaExpressionBuilder().add(operand).add(memberExpression).build(new MemberLookupExpression(tree.location, getResult(operand), getResult(memberExpression)));
},
transformBinaryExpression: function(tree) {
if (tree.operator.isAssignmentOperator())
return this.transformAssignmentExpression(tree);
var left = this.transformAny(tree.left);
var right = this.transformAny(tree.right);
if (left === tree.left && right === tree.right)
return tree;
if (tree.operator.type === OR)
return this.transformOr(left, right);
if (tree.operator.type === AND)
return this.transformAnd(left, right);
var expressions = $traceurRuntime.spread(getExpressions(left), getExpressions(right), [new BinaryExpression(tree.location, getResult(left), tree.operator, getResult(right))]);
return createCommaExpression(expressions);
},
transformAssignmentExpression: function(tree) {
var left = tree.left;
if (left.type === MEMBER_EXPRESSION)
return this.transformAssignMemberExpression(tree);
if (left.type === MEMBER_LOOKUP_EXPRESSION)
return this.transformAssignMemberLookupExpression(tree);
assert(tree.left.type === IDENTIFIER_EXPRESSION);
if (tree.operator.type === EQUAL) {
var left = this.transformAny(left);
var right = this.transformAny(tree.right);
var expressions = $traceurRuntime.spread(getExpressions(right), [createAssignmentExpression(left, getResult(right)), getResult(right)]);
return createCommaExpression(expressions);
}
var right = this.transformAny(tree.right);
var tmp = this.addTempVar();
var binop = createOperatorToken(assignmentOperatorToBinaryOperator(tree.operator.type));
var expressions = $traceurRuntime.spread(getExpressions(right), [createAssignmentExpression(tmp, new BinaryExpression(tree.location, left, binop, getResult(right))), createAssignmentExpression(left, tmp), tmp]);
return createCommaExpression(expressions);
},
transformAssignMemberExpression: function(tree) {
var left = tree.left;
if (tree.operator.type === EQUAL) {
var operand = this.transformAny(left.operand);
var right = this.transformAny(tree.right);
var expressions = $traceurRuntime.spread(getExpressions(operand), getExpressions(right), [new BinaryExpression(tree.location, new MemberExpression(left.location, getResult(operand), left.memberName), tree.operator, getResult(right)), getResult(right)]);
return createCommaExpression(expressions);
}
var operand = this.transformAny(left.operand);
var right = this.transformAny(tree.right);
var tmp = this.addTempVar();
var memberExpression = new MemberExpression(left.location, getResult(operand), left.memberName);
var tmp2 = this.addTempVar();
var binop = createOperatorToken(assignmentOperatorToBinaryOperator(tree.operator.type));
var expressions = $traceurRuntime.spread(getExpressions(operand), getExpressions(right), [createAssignmentExpression(tmp, memberExpression), createAssignmentExpression(tmp2, new BinaryExpression(tree.location, tmp, binop, getResult(right))), createAssignmentExpression(memberExpression, tmp2), tmp2]);
return createCommaExpression(expressions);
},
transformAssignMemberLookupExpression: function(tree) {
var left = tree.left;
if (tree.operator.type === EQUAL) {
var operand = this.transformAny(left.operand);
var memberExpression = this.transformAny(left.memberExpression);
var right = this.transformAny(tree.right);
var expressions = $traceurRuntime.spread(getExpressions(operand), getExpressions(memberExpression), getExpressions(right), [new BinaryExpression(tree.location, new MemberLookupExpression(left.location, getResult(operand), getResult(memberExpression)), tree.operator, getResult(right)), getResult(right)]);
return createCommaExpression(expressions);
}
var operand = this.transformAny(left.operand);
var memberExpression = this.transformAny(left.memberExpression);
var right = this.transformAny(tree.right);
var tmp = this.addTempVar();
var memberLookupExpression = new MemberLookupExpression(left.location, getResult(operand), getResult(memberExpression));
var tmp2 = this.addTempVar();
var binop = createOperatorToken(assignmentOperatorToBinaryOperator(tree.operator.type));
var expressions = $traceurRuntime.spread(getExpressions(operand), getExpressions(memberExpression), getExpressions(right), [createAssignmentExpression(tmp, memberLookupExpression), createAssignmentExpression(tmp2, new BinaryExpression(tree.location, tmp, binop, getResult(right))), createAssignmentExpression(memberLookupExpression, tmp2), tmp2]);
return createCommaExpression(expressions);
},
transformArrayLiteralExpression: function(tree) {
var elements = this.transformList(tree.elements);
if (elements === tree.elements)
return tree;
var builder = this.createCommaExpressionBuilder();
var results = [];
for (var i = 0; i < elements.length; i++) {
builder.add(elements[i]);
results.push(getResult(elements[i]));
}
return builder.build(new ArrayLiteralExpression(tree.location, results));
},
transformObjectLiteralExpression: function(tree) {
var propertyNameAndValues = this.transformList(tree.propertyNameAndValues);
if (propertyNameAndValues === tree.propertyNameAndValues)
return tree;
var builder = this.createCommaExpressionBuilder();
var results = [];
for (var i = 0; i < propertyNameAndValues.length; i++) {
if (propertyNameAndValues[i].type === PROPERTY_NAME_ASSIGNMENT) {
builder.add(propertyNameAndValues[i].value);
results.push(new PropertyNameAssignment(propertyNameAndValues[i].location, propertyNameAndValues[i].name, getResult(propertyNameAndValues[i].value)));
} else {
results.push(propertyNameAndValues[i]);
}
}
return builder.build(new ObjectLiteralExpression(tree.location, results));
},
transformTemplateLiteralExpression: function(tree) {
var operand = this.transformAny(tree.operand);
var elements = this.transformList(tree.elements);
if (!operand && operand === tree.operand && elements === tree.elements)
return tree;
var builder = this.createCommaExpressionBuilder();
if (operand)
builder.add(operand);
var results = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === TEMPLATE_LITERAL_PORTION) {
results.push(elements[i]);
} else {
var expression = elements[i].expression;
builder.add(expression);
var result = getResult(expression);
results.push(new TemplateSubstitution(expression.location, result));
}
}
return builder.build(new TemplateLiteralExpression(tree.location, operand && getResult(operand), results));
},
transformCallExpression: function(tree) {
if (tree.operand.type === MEMBER_EXPRESSION)
return this.transformCallMemberExpression(tree);
if (tree.operand.type === MEMBER_LOOKUP_EXPRESSION)
return this.transformCallMemberLookupExpression(tree);
return this.transformCallAndNew_(tree, CallExpression);
},
transformNewExpression: function(tree) {
return this.transformCallAndNew_(tree, NewExpression);
},
transformCallAndNew_: function(tree, ctor) {
var operand = this.transformAny(tree.operand);
var args = this.transformAny(tree.args);
var builder = this.createCommaExpressionBuilder().add(operand);
var argResults = [];
args.args.forEach((function(arg) {
builder.add(arg);
argResults.push(getResult(arg));
}));
return builder.build(new ctor(tree.location, getResult(operand), new ArgumentList(args.location, argResults)));
},
transformCallMemberExpression: function(tree) {
var memberName = tree.operand.memberName;
var operand = this.transformAny(tree.operand.operand);
var tmp = this.addTempVar();
var memberExpresssion = new MemberExpression(tree.operand.location, getResult(operand), memberName);
var args = this.transformAny(tree.args);
var expressions = $traceurRuntime.spread(getExpressions(operand), [createAssignmentExpression(tmp, memberExpresssion)]);
var argResults = [getResult(operand)];
args.args.forEach((function(arg) {
var $__327;
($__327 = expressions).push.apply($__327, $traceurRuntime.spread(getExpressions(arg)));
argResults.push(getResult(arg));
}));
var callExpression = new CallExpression(tree.location, createMemberExpression(tmp, 'call'), new ArgumentList(args.location, argResults));
var tmp2 = this.addTempVar();
expressions.push(createAssignmentExpression(tmp2, callExpression), tmp2);
return createCommaExpression(expressions);
},
transformCallMemberLookupExpression: function(tree) {
var operand = this.transformAny(tree.operand.operand);
var memberExpression = this.transformAny(tree.operand.memberExpression);
var tmp = this.addTempVar();
var lookupExpresssion = new MemberLookupExpression(tree.operand.location, getResult(operand), getResult(memberExpression));
var args = this.transformAny(tree.args);
var expressions = $traceurRuntime.spread(getExpressions(operand), getExpressions(memberExpression), [createAssignmentExpression(tmp, lookupExpresssion)]);
var argResults = [getResult(operand)];
args.args.forEach((function(arg, i) {
var $__327;
($__327 = expressions).push.apply($__327, $traceurRuntime.spread(getExpressions(arg)));
var result = getResult(arg);
if (tree.args.args[i].type === SPREAD_EXPRESSION)
result = new SpreadExpression(arg.location, result);
argResults.push(result);
}));
var callExpression = new CallExpression(tree.location, createMemberExpression(tmp, 'call'), new ArgumentList(args.location, argResults));
var tmp2 = this.addTempVar();
expressions.push(createAssignmentExpression(tmp2, callExpression), tmp2);
return createCommaExpression(expressions);
},
transformConditionalExpression: function(tree) {
var condition = this.transformAny(tree.condition);
var left = this.transformAny(tree.left);
var right = this.transformAny(tree.right);
if (condition === tree.condition && left === tree.left && right === tree.right)
return tree;
var res = this.addTempVar();
var leftTree = createCommaExpression($traceurRuntime.spread(getExpressions(left), [createAssignmentExpression(res, getResult(left))]));
var rightTree = createCommaExpression($traceurRuntime.spread(getExpressions(right), [createAssignmentExpression(res, getResult(right))]));
var expressions = $traceurRuntime.spread(getExpressions(condition), [new ConditionalExpression(tree.location, getResult(condition), createParenExpression(leftTree), createParenExpression(rightTree)), res]);
return createCommaExpression(expressions);
},
transformOr: function(left, right) {
var res = this.addTempVar();
var leftTree = createCommaExpression([createAssignmentExpression(res, getResult(left))]);
var rightTree = createCommaExpression($traceurRuntime.spread(getExpressions(right), [createAssignmentExpression(res, getResult(right))]));
var expressions = $traceurRuntime.spread(getExpressions(left), [new ConditionalExpression(left.location, getResult(left), createParenExpression(leftTree), createParenExpression(rightTree)), res]);
return createCommaExpression(expressions);
},
transformAnd: function(left, right) {
var res = this.addTempVar();
var leftTree = createCommaExpression($traceurRuntime.spread(getExpressions(right), [createAssignmentExpression(res, getResult(right))]));
var rightTree = createCommaExpression([createAssignmentExpression(res, getResult(left))]);
var expressions = $traceurRuntime.spread(getExpressions(left), [new ConditionalExpression(left.location, getResult(left), createParenExpression(leftTree), createParenExpression(rightTree)), res]);
return createCommaExpression(expressions);
},
transformSpreadExpression: function(tree) {
var expression = this.transformAny(tree.expression);
if (expression === tree.expression)
return tree;
var result = getResult(expression);
if (result.type !== SPREAD_EXPRESSION)
result = new SpreadExpression(result.location, result);
var expressions = $traceurRuntime.spread(getExpressions(expression), [result]);
return createCommaExpression(expressions);
},
createCommaExpressionBuilder: function() {
return new CommaExpressionBuilder(this.addTempVar());
}
}, {}, ParseTreeTransformer);
return {get ExplodeExpressionTransformer() {
return ExplodeExpressionTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/SuperTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/SuperTransformer";
var $__328 = Object.freeze(Object.defineProperties(["$traceurRuntime.superCall(", ", ", ", ", ",\n ", ")"], {raw: {value: Object.freeze(["$traceurRuntime.superCall(", ", ", ", ", ",\n ", ")"])}})),
$__329 = Object.freeze(Object.defineProperties(["$traceurRuntime.superGet(", ", ", ", ", ")"], {raw: {value: Object.freeze(["$traceurRuntime.superGet(", ", ", ", ", ")"])}})),
$__330 = Object.freeze(Object.defineProperties(["$traceurRuntime.superSet(", ", ", ", ", ",\n ", ")"], {raw: {value: Object.freeze(["$traceurRuntime.superSet(", ", ", ", ", ",\n ", ")"])}}));
var ExplodeExpressionTransformer = System.get("traceur@0.0.52/src/codegeneration/ExplodeExpressionTransformer").ExplodeExpressionTransformer;
var $__332 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
FunctionDeclaration = $__332.FunctionDeclaration,
FunctionExpression = $__332.FunctionExpression;
var $__333 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
LITERAL_PROPERTY_NAME = $__333.LITERAL_PROPERTY_NAME,
MEMBER_EXPRESSION = $__333.MEMBER_EXPRESSION,
MEMBER_LOOKUP_EXPRESSION = $__333.MEMBER_LOOKUP_EXPRESSION,
SUPER_EXPRESSION = $__333.SUPER_EXPRESSION;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__335 = System.get("traceur@0.0.52/src/syntax/TokenType"),
EQUAL = $__335.EQUAL,
MINUS_MINUS = $__335.MINUS_MINUS,
PLUS_PLUS = $__335.PLUS_PLUS;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var $__337 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArrayLiteralExpression = $__337.createArrayLiteralExpression,
createIdentifierExpression = $__337.createIdentifierExpression,
createParenExpression = $__337.createParenExpression,
createStringLiteral = $__337.createStringLiteral,
createThisExpression = $__337.createThisExpression;
var parseExpression = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseExpression;
var ExplodeSuperExpression = function ExplodeSuperExpression() {
$traceurRuntime.defaultSuperCall(this, $ExplodeSuperExpression.prototype, arguments);
};
var $ExplodeSuperExpression = ExplodeSuperExpression;
($traceurRuntime.createClass)(ExplodeSuperExpression, {
transformArrowFunctionExpression: function(tree) {
return tree;
},
transformClassExpression: function(tree) {
return tree;
},
transformFunctionBody: function(tree) {
return tree;
}
}, {}, ExplodeExpressionTransformer);
var SuperTransformer = function SuperTransformer(tempVarTransformer, protoName, methodTree, thisName) {
this.tempVarTransformer_ = tempVarTransformer;
this.protoName_ = protoName;
this.method_ = methodTree;
this.superCount_ = 0;
this.thisVar_ = createIdentifierExpression(thisName);
this.inNestedFunc_ = 0;
this.nestedSuperCount_ = 0;
};
var $SuperTransformer = SuperTransformer;
($traceurRuntime.createClass)(SuperTransformer, {
get hasSuper() {
return this.superCount_ > 0;
},
get nestedSuper() {
return this.nestedSuperCount_ > 0;
},
transformFunctionDeclaration: function(tree) {
return this.transformFunction_(tree, FunctionDeclaration);
},
transformFunctionExpression: function(tree) {
return this.transformFunction_(tree, FunctionExpression);
},
transformFunction_: function(tree, constructor) {
var oldSuperCount = this.superCount_;
this.inNestedFunc_++;
var transformedTree = constructor === FunctionExpression ? $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformFunctionExpression", [tree]) : $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformFunctionDeclaration", [tree]);
this.inNestedFunc_--;
if (oldSuperCount !== this.superCount_)
this.nestedSuperCount_ += this.superCount_ - oldSuperCount;
return transformedTree;
},
transformGetAccessor: function(tree) {
return tree;
},
transformSetAccessor: function(tree) {
return tree;
},
transformPropertyMethodAssignMent: function(tree) {
return tree;
},
transformCallExpression: function(tree) {
if (this.method_ && tree.operand.type == SUPER_EXPRESSION) {
this.superCount_++;
assert(this.method_.name.type === LITERAL_PROPERTY_NAME);
var methodName = this.method_.name.literalToken.value;
return this.createSuperCallExpression_(methodName, tree);
}
if (hasSuperMemberExpression(tree.operand)) {
this.superCount_++;
var name;
if (tree.operand.type == MEMBER_EXPRESSION)
name = tree.operand.memberName.value;
else
name = tree.operand.memberExpression;
return this.createSuperCallExpression_(name, tree);
}
return $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformCallExpression", [tree]);
},
createSuperCallExpression_: function(methodName, tree) {
var thisExpr = this.inNestedFunc_ ? this.thisVar_ : createThisExpression();
var args = createArrayLiteralExpression(tree.args.args);
return this.createSuperCallExpression(thisExpr, this.protoName_, methodName, args);
},
createSuperCallExpression: function(thisExpr, protoName, methodName, args) {
return parseExpression($__328, thisExpr, protoName, methodName, args);
},
transformMemberShared_: function(tree, name) {
var thisExpr = this.inNestedFunc_ ? this.thisVar_ : createThisExpression();
return parseExpression($__329, thisExpr, this.protoName_, name);
},
transformMemberExpression: function(tree) {
if (tree.operand.type === SUPER_EXPRESSION) {
this.superCount_++;
return this.transformMemberShared_(tree, createStringLiteral(tree.memberName.value));
}
return $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformMemberExpression", [tree]);
},
transformMemberLookupExpression: function(tree) {
if (tree.operand.type === SUPER_EXPRESSION)
return this.transformMemberShared_(tree, tree.memberExpression);
return $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformMemberLookupExpression", [tree]);
},
transformBinaryExpression: function(tree) {
if (tree.operator.isAssignmentOperator() && hasSuperMemberExpression(tree.left)) {
if (tree.operator.type !== EQUAL) {
var exploded = new ExplodeSuperExpression(this.tempVarTransformer_).transformAny(tree);
return this.transformAny(createParenExpression(exploded));
}
this.superCount_++;
var name = tree.left.type === MEMBER_LOOKUP_EXPRESSION ? tree.left.memberExpression : createStringLiteral(tree.left.memberName.value);
var thisExpr = this.inNestedFunc_ ? this.thisVar_ : createThisExpression();
var right = this.transformAny(tree.right);
return parseExpression($__330, thisExpr, this.protoName_, name, right);
}
return $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformBinaryExpression", [tree]);
},
transformUnaryExpression: function(tree) {
var transformed = this.transformIncrementDecrement_(tree);
if (transformed)
return transformed;
return $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformUnaryExpression", [tree]);
},
transformPostfixExpression: function(tree) {
var transformed = this.transformIncrementDecrement_(tree);
if (transformed)
return transformed;
return $traceurRuntime.superCall(this, $SuperTransformer.prototype, "transformPostfixExpression", [tree]);
},
transformIncrementDecrement_: function(tree) {
var operator = tree.operator;
var operand = tree.operand;
if ((operator.type === PLUS_PLUS || operator.type === MINUS_MINUS) && hasSuperMemberExpression(operand)) {
var exploded = new ExplodeSuperExpression(this.tempVarTransformer_).transformAny(tree);
if (exploded !== tree)
exploded = createParenExpression(exploded);
return this.transformAny(exploded);
}
return null;
}
}, {}, ParseTreeTransformer);
function hasSuperMemberExpression(tree) {
if (tree.type !== MEMBER_EXPRESSION && tree.type !== MEMBER_LOOKUP_EXPRESSION)
return false;
return tree.operand.type === SUPER_EXPRESSION;
}
return {get SuperTransformer() {
return SuperTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ClassTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ClassTransformer";
var $__340 = Object.freeze(Object.defineProperties(["($traceurRuntime.createClass)(", ", ", ", ", ",\n ", ")"], {raw: {value: Object.freeze(["($traceurRuntime.createClass)(", ", ", ", ", ",\n ", ")"])}})),
$__341 = Object.freeze(Object.defineProperties(["($traceurRuntime.createClass)(", ", ", ", ", ")"], {raw: {value: Object.freeze(["($traceurRuntime.createClass)(", ", ", ", ", ")"])}})),
$__342 = Object.freeze(Object.defineProperties(["var ", " = ", ""], {raw: {value: Object.freeze(["var ", " = ", ""])}})),
$__343 = Object.freeze(Object.defineProperties(["var ", " = ", ""], {raw: {value: Object.freeze(["var ", " = ", ""])}})),
$__344 = Object.freeze(Object.defineProperties(["function($__super) {\n var ", " = ", ";\n return ($traceurRuntime.createClass)(", ", ", ",\n ", ", $__super);\n }(", ")"], {raw: {value: Object.freeze(["function($__super) {\n var ", " = ", ";\n return ($traceurRuntime.createClass)(", ", ", ",\n ", ", $__super);\n }(", ")"])}})),
$__345 = Object.freeze(Object.defineProperties(["function() {\n var ", " = ", ";\n return ($traceurRuntime.createClass)(", ", ", ",\n ", ");\n }()"], {raw: {value: Object.freeze(["function() {\n var ", " = ", ";\n return ($traceurRuntime.createClass)(", ", ", ",\n ", ");\n }()"])}})),
$__346 = Object.freeze(Object.defineProperties(["$traceurRuntime.defaultSuperCall(this,\n ", ".prototype, arguments)"], {raw: {value: Object.freeze(["$traceurRuntime.defaultSuperCall(this,\n ", ".prototype, arguments)"])}}));
var AlphaRenamer = System.get("traceur@0.0.52/src/codegeneration/AlphaRenamer").AlphaRenamer;
var CONSTRUCTOR = System.get("traceur@0.0.52/src/syntax/PredefinedName").CONSTRUCTOR;
var $__349 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AnonBlock = $__349.AnonBlock,
ExportDeclaration = $__349.ExportDeclaration,
FunctionExpression = $__349.FunctionExpression,
GetAccessor = $__349.GetAccessor,
PropertyMethodAssignment = $__349.PropertyMethodAssignment,
SetAccessor = $__349.SetAccessor;
var $__350 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
GET_ACCESSOR = $__350.GET_ACCESSOR,
PROPERTY_METHOD_ASSIGNMENT = $__350.PROPERTY_METHOD_ASSIGNMENT,
SET_ACCESSOR = $__350.SET_ACCESSOR;
var SuperTransformer = System.get("traceur@0.0.52/src/codegeneration/SuperTransformer").SuperTransformer;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var VAR = System.get("traceur@0.0.52/src/syntax/TokenType").VAR;
var MakeStrictTransformer = System.get("traceur@0.0.52/src/codegeneration/MakeStrictTransformer").MakeStrictTransformer;
var $__355 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createEmptyParameterList = $__355.createEmptyParameterList,
createExpressionStatement = $__355.createExpressionStatement,
createFunctionBody = $__355.createFunctionBody,
id = $__355.createIdentifierExpression,
createMemberExpression = $__355.createMemberExpression,
createObjectLiteralExpression = $__355.createObjectLiteralExpression,
createParenExpression = $__355.createParenExpression,
createThisExpression = $__355.createThisExpression,
createVariableStatement = $__355.createVariableStatement;
var hasUseStrict = System.get("traceur@0.0.52/src/semantics/util").hasUseStrict;
var $__357 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__357.parseExpression,
parseStatement = $__357.parseStatement,
parseStatements = $__357.parseStatements;
var propName = System.get("traceur@0.0.52/src/staticsemantics/PropName").propName;
function classCall(func, object, staticObject, superClass) {
if (superClass) {
return parseExpression($__340, func, object, staticObject, superClass);
}
return parseExpression($__341, func, object, staticObject);
}
var ClassTransformer = function ClassTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $ClassTransformer.prototype, "constructor", [identifierGenerator]);
this.strictCount_ = 0;
this.state_ = null;
};
var $ClassTransformer = ClassTransformer;
($traceurRuntime.createClass)(ClassTransformer, {
transformExportDeclaration: function(tree) {
var transformed = $traceurRuntime.superCall(this, $ClassTransformer.prototype, "transformExportDeclaration", [tree]);
if (transformed === tree)
return tree;
var declaration = transformed.declaration;
if (declaration instanceof AnonBlock) {
var statements = $traceurRuntime.spread([new ExportDeclaration(null, declaration.statements[0], [])], declaration.statements.slice(1));
return new AnonBlock(null, statements);
}
return transformed;
},
transformModule: function(tree) {
this.strictCount_ = 1;
return $traceurRuntime.superCall(this, $ClassTransformer.prototype, "transformModule", [tree]);
},
transformScript: function(tree) {
this.strictCount_ = +hasUseStrict(tree.scriptItemList);
return $traceurRuntime.superCall(this, $ClassTransformer.prototype, "transformScript", [tree]);
},
transformFunctionBody: function(tree) {
var useStrict = +hasUseStrict(tree.statements);
this.strictCount_ += useStrict;
var result = $traceurRuntime.superCall(this, $ClassTransformer.prototype, "transformFunctionBody", [tree]);
this.strictCount_ -= useStrict;
return result;
},
makeStrict_: function(tree) {
if (this.strictCount_)
return tree;
return MakeStrictTransformer.transformTree(tree);
},
transformClassElements_: function(tree, internalName) {
var $__359 = this;
var oldState = this.state_;
this.state_ = {hasSuper: false};
var superClass = this.transformAny(tree.superClass);
var hasConstructor = false;
var protoElements = [],
staticElements = [];
var constructorBody,
constructorParams;
tree.elements.forEach((function(tree) {
var elements,
homeObject;
if (tree.isStatic) {
elements = staticElements;
homeObject = internalName;
} else {
elements = protoElements;
homeObject = createMemberExpression(internalName, 'prototype');
}
switch (tree.type) {
case GET_ACCESSOR:
elements.push($__359.transformGetAccessor_(tree, homeObject));
break;
case SET_ACCESSOR:
elements.push($__359.transformSetAccessor_(tree, homeObject));
break;
case PROPERTY_METHOD_ASSIGNMENT:
var transformed = $__359.transformPropertyMethodAssignment_(tree, homeObject);
if (!tree.isStatic && propName(tree) === CONSTRUCTOR) {
hasConstructor = true;
constructorParams = transformed.parameterList;
constructorBody = transformed.body;
} else {
elements.push(transformed);
}
break;
default:
throw new Error(("Unexpected class element: " + tree.type));
}
}));
var object = createObjectLiteralExpression(protoElements);
var staticObject = createObjectLiteralExpression(staticElements);
var func;
if (!hasConstructor) {
func = this.getDefaultConstructor_(tree, internalName);
} else {
func = new FunctionExpression(tree.location, tree.name, false, constructorParams, null, [], constructorBody);
}
var state = this.state_;
this.state_ = oldState;
return {
func: func,
superClass: superClass,
object: object,
staticObject: staticObject,
hasSuper: state.hasSuper
};
},
transformClassDeclaration: function(tree) {
var name = tree.name.identifierToken;
var internalName = id(("$" + name));
var renamed = AlphaRenamer.rename(tree, name.value, internalName.identifierToken.value);
var referencesClassName = renamed !== tree;
var tree = renamed;
var $__361 = $traceurRuntime.assertObject(this.transformClassElements_(tree, internalName)),
func = $__361.func,
hasSuper = $__361.hasSuper,
object = $__361.object,
staticObject = $__361.staticObject,
superClass = $__361.superClass;
var statements = parseStatements($__342, name, func);
var expr = classCall(name, object, staticObject, superClass);
if (hasSuper || referencesClassName) {
statements.push(parseStatement($__343, internalName, name));
}
statements.push(createExpressionStatement(expr));
var anonBlock = new AnonBlock(null, statements);
return this.makeStrict_(anonBlock);
},
transformClassExpression: function(tree) {
this.pushTempScope();
var name;
if (tree.name)
name = tree.name.identifierToken;
else
name = id(this.getTempIdentifier());
var $__361 = $traceurRuntime.assertObject(this.transformClassElements_(tree, name)),
func = $__361.func,
hasSuper = $__361.hasSuper,
object = $__361.object,
staticObject = $__361.staticObject,
superClass = $__361.superClass;
var expression;
if (hasSuper || tree.name) {
if (superClass) {
expression = parseExpression($__344, name, func, name, object, staticObject, superClass);
} else {
expression = parseExpression($__345, name, func, name, object, staticObject);
}
} else {
expression = classCall(func, object, staticObject, superClass);
}
this.popTempScope();
return createParenExpression(this.makeStrict_(expression));
},
transformPropertyMethodAssignment_: function(tree, internalName) {
var parameterList = this.transformAny(tree.parameterList);
var body = this.transformSuperInFunctionBody_(tree, tree.body, internalName);
if (!tree.isStatic && parameterList === tree.parameterList && body === tree.body) {
return tree;
}
var isStatic = false;
return new PropertyMethodAssignment(tree.location, isStatic, tree.functionKind, tree.name, parameterList, tree.typeAnnotation, tree.annotations, body);
},
transformGetAccessor_: function(tree, internalName) {
var body = this.transformSuperInFunctionBody_(tree, tree.body, internalName);
if (!tree.isStatic && body === tree.body)
return tree;
return new GetAccessor(tree.location, false, tree.name, tree.typeAnnotation, tree.annotations, body);
},
transformSetAccessor_: function(tree, internalName) {
var parameterList = this.transformAny(tree.parameterList);
var body = this.transformSuperInFunctionBody_(tree, tree.body, internalName);
if (!tree.isStatic && body === tree.body)
return tree;
return new SetAccessor(tree.location, false, tree.name, parameterList, tree.annotations, body);
},
transformSuperInFunctionBody_: function(methodTree, tree, internalName) {
this.pushTempScope();
var thisName = this.getTempIdentifier();
var thisDecl = createVariableStatement(VAR, thisName, createThisExpression());
var superTransformer = new SuperTransformer(this, internalName, methodTree, thisName);
var transformedTree = superTransformer.transformFunctionBody(this.transformFunctionBody(tree));
if (superTransformer.hasSuper)
this.state_.hasSuper = true;
this.popTempScope();
if (superTransformer.nestedSuper)
return createFunctionBody([thisDecl].concat(transformedTree.statements));
return transformedTree;
},
getDefaultConstructor_: function(tree, internalName) {
var constructorParams = createEmptyParameterList();
var constructorBody;
if (tree.superClass) {
var statement = parseStatement($__346, internalName);
constructorBody = createFunctionBody([statement]);
this.state_.hasSuper = true;
} else {
constructorBody = createFunctionBody([]);
}
return new FunctionExpression(tree.location, tree.name, false, constructorParams, null, [], constructorBody);
}
}, {}, TempVarTransformer);
return {get ClassTransformer() {
return ClassTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/CommonJsModuleTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/CommonJsModuleTransformer";
var $__362 = Object.freeze(Object.defineProperties(["module.exports = function() {\n ", "\n }.call(", ");"], {raw: {value: Object.freeze(["module.exports = function() {\n ", "\n }.call(", ");"])}})),
$__363 = Object.freeze(Object.defineProperties(["Object.defineProperties(exports, ", ");"], {raw: {value: Object.freeze(["Object.defineProperties(exports, ", ");"])}})),
$__364 = Object.freeze(Object.defineProperties(["{get: ", "}"], {raw: {value: Object.freeze(["{get: ", "}"])}})),
$__365 = Object.freeze(Object.defineProperties(["{value: ", "}"], {raw: {value: Object.freeze(["{value: ", "}"])}})),
$__366 = Object.freeze(Object.defineProperties(["require(", ")"], {raw: {value: Object.freeze(["require(", ")"])}})),
$__367 = Object.freeze(Object.defineProperties(["__esModule: true"], {raw: {value: Object.freeze(["__esModule: true"])}}));
var ModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/ModuleTransformer").ModuleTransformer;
var $__369 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
GET_ACCESSOR = $__369.GET_ACCESSOR,
OBJECT_LITERAL_EXPRESSION = $__369.OBJECT_LITERAL_EXPRESSION,
PROPERTY_NAME_ASSIGNMENT = $__369.PROPERTY_NAME_ASSIGNMENT,
RETURN_STATEMENT = $__369.RETURN_STATEMENT;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var globalThis = System.get("traceur@0.0.52/src/codegeneration/globalThis").default;
var $__372 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__372.parseExpression,
parsePropertyDefinition = $__372.parsePropertyDefinition,
parseStatement = $__372.parseStatement,
parseStatements = $__372.parseStatements;
var scopeContainsThis = System.get("traceur@0.0.52/src/codegeneration/scopeContainsThis").default;
var $__374 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createEmptyParameterList = $__374.createEmptyParameterList,
createFunctionExpression = $__374.createFunctionExpression,
createObjectLiteralExpression = $__374.createObjectLiteralExpression,
createPropertyNameAssignment = $__374.createPropertyNameAssignment;
var prependStatements = System.get("traceur@0.0.52/src/codegeneration/PrependStatements").prependStatements;
var CommonJsModuleTransformer = function CommonJsModuleTransformer() {
$traceurRuntime.defaultSuperCall(this, $CommonJsModuleTransformer.prototype, arguments);
};
var $CommonJsModuleTransformer = CommonJsModuleTransformer;
($traceurRuntime.createClass)(CommonJsModuleTransformer, {
wrapModule: function(statements) {
var needsIife = statements.some(scopeContainsThis);
if (needsIife) {
return parseStatements($__362, statements, globalThis());
}
var last = statements[statements.length - 1];
statements = statements.slice(0, -1);
assert(last.type === RETURN_STATEMENT);
var exportObject = last.expression;
if (this.hasExports()) {
var descriptors = this.transformObjectLiteralToDescriptors(exportObject);
var exportStatement = parseStatement($__363, descriptors);
statements = prependStatements(statements, exportStatement);
}
return statements;
},
transformObjectLiteralToDescriptors: function(literalTree) {
assert(literalTree.type === OBJECT_LITERAL_EXPRESSION);
var props = literalTree.propertyNameAndValues.map((function(exp) {
var descriptor;
switch (exp.type) {
case GET_ACCESSOR:
var getterFunction = createFunctionExpression(createEmptyParameterList(), exp.body);
descriptor = parseExpression($__364, getterFunction);
break;
case PROPERTY_NAME_ASSIGNMENT:
descriptor = parseExpression($__365, exp.value);
break;
default:
throw new Error(("Unexpected property type " + exp.type));
}
return createPropertyNameAssignment(exp.name, descriptor);
}));
return createObjectLiteralExpression(props);
},
transformModuleSpecifier: function(tree) {
return parseExpression($__366, tree.token);
},
getExportProperties: function() {
var properties = $traceurRuntime.superCall(this, $CommonJsModuleTransformer.prototype, "getExportProperties", []);
if (this.exportVisitor_.hasExports())
properties.push(parsePropertyDefinition($__367));
return properties;
}
}, {}, ModuleTransformer);
return {get CommonJsModuleTransformer() {
return CommonJsModuleTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ParameterTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ParameterTransformer";
var FunctionBody = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").FunctionBody;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var prependStatements = System.get("traceur@0.0.52/src/codegeneration/PrependStatements").prependStatements;
var stack = [];
var ParameterTransformer = function ParameterTransformer() {
$traceurRuntime.defaultSuperCall(this, $ParameterTransformer.prototype, arguments);
};
var $ParameterTransformer = ParameterTransformer;
($traceurRuntime.createClass)(ParameterTransformer, {
transformArrowFunctionExpression: function(tree) {
stack.push([]);
return $traceurRuntime.superCall(this, $ParameterTransformer.prototype, "transformArrowFunctionExpression", [tree]);
},
transformFunctionDeclaration: function(tree) {
stack.push([]);
return $traceurRuntime.superCall(this, $ParameterTransformer.prototype, "transformFunctionDeclaration", [tree]);
},
transformFunctionExpression: function(tree) {
stack.push([]);
return $traceurRuntime.superCall(this, $ParameterTransformer.prototype, "transformFunctionExpression", [tree]);
},
transformGetAccessor: function(tree) {
stack.push([]);
return $traceurRuntime.superCall(this, $ParameterTransformer.prototype, "transformGetAccessor", [tree]);
},
transformSetAccessor: function(tree) {
stack.push([]);
return $traceurRuntime.superCall(this, $ParameterTransformer.prototype, "transformSetAccessor", [tree]);
},
transformPropertyMethodAssignment: function(tree) {
stack.push([]);
return $traceurRuntime.superCall(this, $ParameterTransformer.prototype, "transformPropertyMethodAssignment", [tree]);
},
transformFunctionBody: function(tree) {
var transformedTree = $traceurRuntime.superCall(this, $ParameterTransformer.prototype, "transformFunctionBody", [tree]);
var statements = stack.pop();
if (!statements.length)
return transformedTree;
statements = prependStatements.apply(null, $traceurRuntime.spread([transformedTree.statements], statements));
return new FunctionBody(transformedTree.location, statements);
},
get parameterStatements() {
return stack[stack.length - 1];
}
}, {}, TempVarTransformer);
return {get ParameterTransformer() {
return ParameterTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/DefaultParametersTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/DefaultParametersTransformer";
var $__381 = System.get("traceur@0.0.52/src/semantics/util"),
isUndefined = $__381.isUndefined,
isVoidExpression = $__381.isVoidExpression;
var FormalParameterList = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").FormalParameterList;
var ParameterTransformer = System.get("traceur@0.0.52/src/codegeneration/ParameterTransformer").ParameterTransformer;
var ARGUMENTS = System.get("traceur@0.0.52/src/syntax/PredefinedName").ARGUMENTS;
var $__385 = System.get("traceur@0.0.52/src/syntax/TokenType"),
NOT_EQUAL_EQUAL = $__385.NOT_EQUAL_EQUAL,
VAR = $__385.VAR;
var $__386 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createBinaryExpression = $__386.createBinaryExpression,
createConditionalExpression = $__386.createConditionalExpression,
createIdentifierExpression = $__386.createIdentifierExpression,
createMemberLookupExpression = $__386.createMemberLookupExpression,
createNumberLiteral = $__386.createNumberLiteral,
createOperatorToken = $__386.createOperatorToken,
createVariableStatement = $__386.createVariableStatement,
createVoid0 = $__386.createVoid0;
function createDefaultAssignment(index, binding, initializer) {
var argumentsExpression = createMemberLookupExpression(createIdentifierExpression(ARGUMENTS), createNumberLiteral(index));
var assignmentExpression;
if (initializer === null || isUndefined(initializer) || isVoidExpression(initializer)) {
assignmentExpression = argumentsExpression;
} else {
assignmentExpression = createConditionalExpression(createBinaryExpression(argumentsExpression, createOperatorToken(NOT_EQUAL_EQUAL), createVoid0()), argumentsExpression, initializer);
}
return createVariableStatement(VAR, binding, assignmentExpression);
}
var DefaultParametersTransformer = function DefaultParametersTransformer() {
$traceurRuntime.defaultSuperCall(this, $DefaultParametersTransformer.prototype, arguments);
};
var $DefaultParametersTransformer = DefaultParametersTransformer;
($traceurRuntime.createClass)(DefaultParametersTransformer, {transformFormalParameterList: function(tree) {
var parameters = [];
var changed = false;
var defaultToUndefined = false;
for (var i = 0; i < tree.parameters.length; i++) {
var param = this.transformAny(tree.parameters[i]);
if (param !== tree.parameters[i])
changed = true;
if (param.isRestParameter() || !param.parameter.initializer && !defaultToUndefined) {
parameters.push(param);
} else {
defaultToUndefined = true;
changed = true;
this.parameterStatements.push(createDefaultAssignment(i, param.parameter.binding, param.parameter.initializer));
}
}
if (!changed)
return tree;
return new FormalParameterList(tree.location, parameters);
}}, {}, ParameterTransformer);
return {get DefaultParametersTransformer() {
return DefaultParametersTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ForOfTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ForOfTransformer";
var $__388 = Object.freeze(Object.defineProperties(["", " = ", ".value;"], {raw: {value: Object.freeze(["", " = ", ".value;"])}})),
$__389 = Object.freeze(Object.defineProperties(["\n for (var ", " =\n ", "[Symbol.iterator](),\n ", ";\n !(", " = ", ".next()).done; ) {\n ", ";\n ", ";\n }"], {raw: {value: Object.freeze(["\n for (var ", " =\n ", "[Symbol.iterator](),\n ", ";\n !(", " = ", ".next()).done; ) {\n ", ";\n ", ";\n }"])}}));
var VARIABLE_DECLARATION_LIST = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType").VARIABLE_DECLARATION_LIST;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__392 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
id = $__392.createIdentifierExpression,
createMemberExpression = $__392.createMemberExpression,
createVariableStatement = $__392.createVariableStatement;
var parseStatement = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatement;
var ForOfTransformer = function ForOfTransformer() {
$traceurRuntime.defaultSuperCall(this, $ForOfTransformer.prototype, arguments);
};
var $ForOfTransformer = ForOfTransformer;
($traceurRuntime.createClass)(ForOfTransformer, {transformForOfStatement: function(original) {
var tree = $traceurRuntime.superCall(this, $ForOfTransformer.prototype, "transformForOfStatement", [original]);
var iter = id(this.getTempIdentifier());
var result = id(this.getTempIdentifier());
var assignment;
if (tree.initializer.type === VARIABLE_DECLARATION_LIST) {
assignment = createVariableStatement(tree.initializer.declarationType, tree.initializer.declarations[0].lvalue, createMemberExpression(result, 'value'));
} else {
assignment = parseStatement($__388, tree.initializer, result);
}
return parseStatement($__389, iter, tree.collection, result, result, iter, assignment, tree.body);
}}, {}, TempVarTransformer);
return {get ForOfTransformer() {
return ForOfTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/GeneratorComprehensionTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/GeneratorComprehensionTransformer";
var ComprehensionTransformer = System.get("traceur@0.0.52/src/codegeneration/ComprehensionTransformer").ComprehensionTransformer;
var createYieldStatement = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createYieldStatement;
var GeneratorComprehensionTransformer = function GeneratorComprehensionTransformer() {
$traceurRuntime.defaultSuperCall(this, $GeneratorComprehensionTransformer.prototype, arguments);
};
var $GeneratorComprehensionTransformer = GeneratorComprehensionTransformer;
($traceurRuntime.createClass)(GeneratorComprehensionTransformer, {transformGeneratorComprehension: function(tree) {
var expression = this.transformAny(tree.expression);
var statement = createYieldStatement(expression);
var isGenerator = true;
return this.transformComprehension(tree, statement, isGenerator);
}}, {}, ComprehensionTransformer);
return {get GeneratorComprehensionTransformer() {
return GeneratorComprehensionTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/State", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/State";
var $__398 = Object.freeze(Object.defineProperties(["$ctx.finallyFallThrough = ", ""], {raw: {value: Object.freeze(["$ctx.finallyFallThrough = ", ""])}}));
var $__399 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createAssignStateStatement = $__399.createAssignStateStatement,
createBreakStatement = $__399.createBreakStatement,
createCaseClause = $__399.createCaseClause,
createNumberLiteral = $__399.createNumberLiteral;
var parseStatement = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatement;
var State = function State(id) {
this.id = id;
};
($traceurRuntime.createClass)(State, {
transformMachineState: function(enclosingFinally, machineEndState, reporter) {
return createCaseClause(createNumberLiteral(this.id), this.transform(enclosingFinally, machineEndState, reporter));
},
transformBreak: function(labelSet, breakState) {
return this;
},
transformBreakOrContinue: function(labelSet) {
var breakState = arguments[1];
var continueState = arguments[2];
return this;
}
}, {});
State.START_STATE = 0;
State.INVALID_STATE = -1;
State.END_STATE = -2;
State.RETHROW_STATE = -3;
State.generateJump = function(enclosingFinally, fallThroughState) {
return $traceurRuntime.spread(State.generateAssignState(enclosingFinally, fallThroughState), [createBreakStatement()]);
};
State.generateAssignState = function(enclosingFinally, fallThroughState) {
var assignState;
if (State.isFinallyExit(enclosingFinally, fallThroughState)) {
assignState = generateAssignStateOutOfFinally(enclosingFinally, fallThroughState);
} else {
assignState = [createAssignStateStatement(fallThroughState)];
}
return assignState;
};
State.isFinallyExit = function(enclosingFinally, destination) {
return enclosingFinally != null && enclosingFinally.tryStates.indexOf(destination) < 0;
};
function generateAssignStateOutOfFinally(enclosingFinally, destination) {
var finallyState = enclosingFinally.finallyState;
return [createAssignStateStatement(finallyState), parseStatement($__398, destination)];
}
State.replaceStateList = function(oldStates, oldState, newState) {
var states = [];
for (var i = 0; i < oldStates.length; i++) {
states.push(State.replaceStateId(oldStates[i], oldState, newState));
}
return states;
};
State.replaceStateId = function(current, oldState, newState) {
return current == oldState ? newState : current;
};
State.replaceAllStates = function(exceptionBlocks, oldState, newState) {
var result = [];
for (var i = 0; i < exceptionBlocks.length; i++) {
result.push(exceptionBlocks[i].replaceState(oldState, newState));
}
return result;
};
return {get State() {
return State;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/TryState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/TryState";
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var Kind = {
CATCH: 'catch',
FINALLY: 'finally'
};
var TryState = function TryState(kind, tryStates, nestedTrys) {
this.kind = kind;
this.tryStates = tryStates;
this.nestedTrys = nestedTrys;
};
($traceurRuntime.createClass)(TryState, {
replaceAllStates: function(oldState, newState) {
return State.replaceStateList(this.tryStates, oldState, newState);
},
replaceNestedTrys: function(oldState, newState) {
var states = [];
for (var i = 0; i < this.nestedTrys.length; i++) {
states.push(this.nestedTrys[i].replaceState(oldState, newState));
}
return states;
}
}, {});
TryState.Kind = Kind;
return {get TryState() {
return TryState;
}};
});
System.register("traceur@0.0.52/src/syntax/trees/StateMachine", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/trees/StateMachine";
var ParseTree = System.get("traceur@0.0.52/src/syntax/trees/ParseTree").ParseTree;
var STATE_MACHINE = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType").STATE_MACHINE;
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var TryState = System.get("traceur@0.0.52/src/codegeneration/generator/TryState").TryState;
function addCatchOrFinallyStates(kind, enclosingMap, tryStates) {
for (var i = 0; i < tryStates.length; i++) {
var tryState = tryStates[i];
if (tryState.kind == kind) {
for (var j = 0; j < tryState.tryStates.length; j++) {
var id = tryState.tryStates[j];
enclosingMap[id] = tryState;
}
}
addCatchOrFinallyStates(kind, enclosingMap, tryState.nestedTrys);
}
}
function addAllCatchStates(tryStates, catches) {
for (var i = 0; i < tryStates.length; i++) {
var tryState = tryStates[i];
if (tryState.kind == TryState.Kind.CATCH) {
catches.push(tryState);
}
addAllCatchStates(tryState.nestedTrys, catches);
}
}
var StateMachine = function StateMachine(startState, fallThroughState, states, exceptionBlocks) {
this.location = null;
this.startState = startState;
this.fallThroughState = fallThroughState;
this.states = states;
this.exceptionBlocks = exceptionBlocks;
};
var $StateMachine = StateMachine;
($traceurRuntime.createClass)(StateMachine, {
get type() {
return STATE_MACHINE;
},
transform: function(transformer) {
return transformer.transformStateMachine(this);
},
visit: function(visitor) {
visitor.visitStateMachine(this);
},
getAllStateIDs: function() {
var result = [];
for (var i = 0; i < this.states.length; i++) {
result.push(this.states[i].id);
}
return result;
},
getEnclosingFinallyMap: function() {
var enclosingMap = Object.create(null);
addCatchOrFinallyStates(TryState.Kind.FINALLY, enclosingMap, this.exceptionBlocks);
return enclosingMap;
},
allCatchStates: function() {
var catches = [];
addAllCatchStates(this.exceptionBlocks, catches);
return catches;
},
replaceStateId: function(oldState, newState) {
return new $StateMachine(State.replaceStateId(this.startState, oldState, newState), State.replaceStateId(this.fallThroughState, oldState, newState), State.replaceAllStates(this.states, oldState, newState), State.replaceAllStates(this.exceptionBlocks, oldState, newState));
},
replaceStartState: function(newState) {
return this.replaceStateId(this.startState, newState);
},
replaceFallThroughState: function(newState) {
return this.replaceStateId(this.fallThroughState, newState);
},
append: function(nextMachine) {
var states = $traceurRuntime.spread(this.states);
for (var i = 0; i < nextMachine.states.length; i++) {
var otherState = nextMachine.states[i];
states.push(otherState.replaceState(nextMachine.startState, this.fallThroughState));
}
var exceptionBlocks = $traceurRuntime.spread(this.exceptionBlocks);
for (var i = 0; i < nextMachine.exceptionBlocks.length; i++) {
var tryState = nextMachine.exceptionBlocks[i];
exceptionBlocks.push(tryState.replaceState(nextMachine.startState, this.fallThroughState));
}
return new $StateMachine(this.startState, nextMachine.fallThroughState, states, exceptionBlocks);
}
}, {}, ParseTree);
return {get StateMachine() {
return StateMachine;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/AwaitState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/AwaitState";
var $__409 = Object.freeze(Object.defineProperties(["Promise.resolve(", ").then(\n $ctx.createCallback(", "), $ctx.errback);\n return"], {raw: {value: Object.freeze(["Promise.resolve(", ").then(\n $ctx.createCallback(", "), $ctx.errback);\n return"])}}));
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var parseStatements = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatements;
var AwaitState = function AwaitState(id, callbackState, expression) {
$traceurRuntime.superCall(this, $AwaitState.prototype, "constructor", [id]), this.callbackState = callbackState;
this.expression = expression;
this.statements_ = null;
};
var $AwaitState = AwaitState;
($traceurRuntime.createClass)(AwaitState, {
get statements() {
if (!this.statements_) {
this.statements_ = parseStatements($__409, this.expression, this.callbackState);
}
return this.statements_;
},
replaceState: function(oldState, newState) {
return new $AwaitState(State.replaceStateId(this.id, oldState, newState), State.replaceStateId(this.callbackState, oldState, newState), this.expression);
},
transform: function(enclosingFinally, machineEndState, reporter) {
return this.statements;
}
}, {}, State);
return {get AwaitState() {
return AwaitState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/HoistVariablesTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/HoistVariablesTransformer";
var $__413 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AnonBlock = $__413.AnonBlock,
Catch = $__413.Catch,
FunctionBody = $__413.FunctionBody,
ForInStatement = $__413.ForInStatement,
ForOfStatement = $__413.ForOfStatement,
ForStatement = $__413.ForStatement,
VariableDeclarationList = $__413.VariableDeclarationList,
VariableStatement = $__413.VariableStatement;
var $__414 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
OBJECT_PATTERN = $__414.OBJECT_PATTERN,
VARIABLE_DECLARATION_LIST = $__414.VARIABLE_DECLARATION_LIST;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var VAR = System.get("traceur@0.0.52/src/syntax/TokenType").VAR;
var $__417 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createAssignmentExpression = $__417.createAssignmentExpression,
createCommaExpression = $__417.createCommaExpression,
createExpressionStatement = $__417.createExpressionStatement,
id = $__417.createIdentifierExpression,
createParenExpression = $__417.createParenExpression,
createVariableDeclaration = $__417.createVariableDeclaration;
var prependStatements = System.get("traceur@0.0.52/src/codegeneration/PrependStatements").prependStatements;
var HoistVariablesTransformer = function HoistVariablesTransformer() {
$traceurRuntime.superCall(this, $HoistVariablesTransformer.prototype, "constructor", []);
this.hoistedVariables_ = Object.create(null);
this.keepBindingIdentifiers_ = false;
this.inBlockOrFor_ = false;
};
var $HoistVariablesTransformer = HoistVariablesTransformer;
($traceurRuntime.createClass)(HoistVariablesTransformer, {
transformFunctionBody: function(tree) {
var statements = this.transformList(tree.statements);
if (statements === tree.statements)
return tree;
var prepended = this.prependVariables(statements);
return new FunctionBody(tree.location, prepended);
},
addVariable: function(name) {
this.hoistedVariables_[name] = true;
},
hasVariables: function() {
for (var key in this.hoistedVariables_) {
return true;
}
return false;
},
getVariableNames: function() {
return Object.keys(this.hoistedVariables_);
},
getVariableStatement: function() {
if (!this.hasVariables())
return null;
var declarations = this.getVariableNames().map((function(name) {
return createVariableDeclaration(name, null);
}));
return new VariableStatement(null, new VariableDeclarationList(null, VAR, declarations));
},
prependVariables: function(statements) {
if (!this.hasVariables())
return statements;
return prependStatements(statements, this.getVariableStatement());
},
transformVariableStatement: function(tree) {
var declarations = this.transformAny(tree.declarations);
if (declarations == tree.declarations)
return tree;
if (declarations === null)
return new AnonBlock(null, []);
if (declarations.type === VARIABLE_DECLARATION_LIST)
return new VariableStatement(tree.location, declarations);
return createExpressionStatement(declarations);
},
transformVariableDeclaration: function(tree) {
var lvalue = this.transformAny(tree.lvalue);
var initializer = this.transformAny(tree.initializer);
if (initializer) {
var expression = createAssignmentExpression(lvalue, initializer);
if (lvalue.type === OBJECT_PATTERN)
expression = createParenExpression(expression);
return expression;
}
return null;
},
transformObjectPattern: function(tree) {
var keepBindingIdentifiers = this.keepBindingIdentifiers_;
this.keepBindingIdentifiers_ = true;
var transformed = $traceurRuntime.superCall(this, $HoistVariablesTransformer.prototype, "transformObjectPattern", [tree]);
this.keepBindingIdentifiers_ = keepBindingIdentifiers;
return transformed;
},
transformArrayPattern: function(tree) {
var keepBindingIdentifiers = this.keepBindingIdentifiers_;
this.keepBindingIdentifiers_ = true;
var transformed = $traceurRuntime.superCall(this, $HoistVariablesTransformer.prototype, "transformArrayPattern", [tree]);
this.keepBindingIdentifiers_ = keepBindingIdentifiers;
return transformed;
},
transformBindingIdentifier: function(tree) {
var idToken = tree.identifierToken;
this.addVariable(idToken.value);
if (this.keepBindingIdentifiers_)
return tree;
return id(idToken);
},
transformVariableDeclarationList: function(tree) {
if (tree.declarationType === VAR || !this.inBlockOrFor_) {
var expressions = this.transformList(tree.declarations);
expressions = expressions.filter((function(tree) {
return tree;
}));
if (expressions.length === 0)
return null;
if (expressions.length == 1)
return expressions[0];
return createCommaExpression(expressions);
}
return tree;
},
transformCatch: function(tree) {
var catchBody = this.transformAny(tree.catchBody);
if (catchBody === tree.catchBody)
return tree;
return new Catch(tree.location, tree.binding, catchBody);
},
transformForInStatement: function(tree) {
return this.transformLoop_(tree, ForInStatement);
},
transformForOfStatement: function(tree) {
return this.transformLoop_(tree, ForOfStatement);
},
transformLoop_: function(tree, ctor) {
var initializer = this.transformLoopIninitaliser_(tree.initializer);
var collection = this.transformAny(tree.collection);
var body = this.transformAny(tree.body);
if (initializer === tree.initializer && collection === tree.collection && body === tree.body) {
return tree;
}
return new ctor(tree.location, initializer, collection, body);
},
transformLoopIninitaliser_: function(tree) {
if (tree.type !== VARIABLE_DECLARATION_LIST || tree.declarationType !== VAR)
return tree;
return this.transformAny(tree.declarations[0].lvalue);
},
transformForStatement: function(tree) {
var inBlockOrFor = this.inBlockOrFor_;
this.inBlockOrFor_ = true;
var initializer = this.transformAny(tree.initializer);
this.inBlockOrFor_ = inBlockOrFor;
var condition = this.transformAny(tree.condition);
var increment = this.transformAny(tree.increment);
var body = this.transformAny(tree.body);
if (initializer === tree.initializer && condition === tree.condition && increment === tree.increment && body === tree.body) {
return tree;
}
return new ForStatement(tree.location, initializer, condition, increment, body);
},
transformBlock: function(tree) {
var inBlockOrFor = this.inBlockOrFor_;
this.inBlockOrFor_ = true;
tree = $traceurRuntime.superCall(this, $HoistVariablesTransformer.prototype, "transformBlock", [tree]);
this.inBlockOrFor_ = inBlockOrFor;
return tree;
},
addMachineVariable: function(name) {
this.machineVariables_[name] = true;
},
transformClassDeclaration: function(tree) {
return tree;
},
transformClassExpression: function(tree) {
return tree;
},
transformFunctionDeclaration: function(tree) {
return tree;
},
transformFunctionExpression: function(tree) {
return tree;
},
transformGetAccessor: function(tree) {
return tree;
},
transformSetAccessor: function(tree) {
return tree;
},
transformPropertyMethodAssignment: function(tree) {
return tree;
},
transformArrowFunctionExpression: function(tree) {
return tree;
},
transformComprehensionFor: function(tree) {
return tree;
}
}, {}, ParseTreeTransformer);
var $__default = HoistVariablesTransformer;
return {get default() {
return $__default;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/FallThroughState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/FallThroughState";
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var FallThroughState = function FallThroughState(id, fallThroughState, statements) {
$traceurRuntime.superCall(this, $FallThroughState.prototype, "constructor", [id]);
this.fallThroughState = fallThroughState;
this.statements = statements;
};
var $FallThroughState = FallThroughState;
($traceurRuntime.createClass)(FallThroughState, {
replaceState: function(oldState, newState) {
return new $FallThroughState(State.replaceStateId(this.id, oldState, newState), State.replaceStateId(this.fallThroughState, oldState, newState), this.statements);
},
transform: function(enclosingFinally, machineEndState, reporter) {
return $traceurRuntime.spread(this.statements, State.generateJump(enclosingFinally, this.fallThroughState));
}
}, {}, State);
return {get FallThroughState() {
return FallThroughState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/BreakState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/BreakState";
var FallThroughState = System.get("traceur@0.0.52/src/codegeneration/generator/FallThroughState").FallThroughState;
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var BreakState = function BreakState(id, label) {
$traceurRuntime.superCall(this, $BreakState.prototype, "constructor", [id]);
this.label = label;
};
var $BreakState = BreakState;
($traceurRuntime.createClass)(BreakState, {
replaceState: function(oldState, newState) {
return new $BreakState(State.replaceStateId(this.id, oldState, newState), this.label);
},
transform: function(enclosingFinally, machineEndState, reporter) {
throw new Error('These should be removed before the transform step');
},
transformBreak: function(labelSet) {
var breakState = arguments[1];
if (this.label == null)
return new FallThroughState(this.id, breakState, []);
if (this.label in labelSet) {
return new FallThroughState(this.id, labelSet[this.label].fallThroughState, []);
}
return this;
},
transformBreakOrContinue: function(labelSet) {
var breakState = arguments[1];
var continueState = arguments[2];
return this.transformBreak(labelSet, breakState);
}
}, {}, State);
return {get BreakState() {
return BreakState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/ContinueState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/ContinueState";
var FallThroughState = System.get("traceur@0.0.52/src/codegeneration/generator/FallThroughState").FallThroughState;
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var ContinueState = function ContinueState(id, label) {
$traceurRuntime.superCall(this, $ContinueState.prototype, "constructor", [id]);
this.label = label;
};
var $ContinueState = ContinueState;
($traceurRuntime.createClass)(ContinueState, {
replaceState: function(oldState, newState) {
return new $ContinueState(State.replaceStateId(this.id, oldState, newState), this.label);
},
transform: function(enclosingFinally, machineEndState, reporter) {
throw new Error('These should be removed before the transform step');
},
transformBreakOrContinue: function(labelSet) {
var breakState = arguments[1];
var continueState = arguments[2];
if (this.label == null)
return new FallThroughState(this.id, continueState, []);
if (this.label in labelSet) {
return new FallThroughState(this.id, labelSet[this.label].continueState, []);
}
return this;
}
}, {}, State);
return {get ContinueState() {
return ContinueState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/BreakContinueTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/BreakContinueTransformer";
var BreakState = System.get("traceur@0.0.52/src/codegeneration/generator/BreakState").BreakState;
var ContinueState = System.get("traceur@0.0.52/src/codegeneration/generator/ContinueState").ContinueState;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var StateMachine = System.get("traceur@0.0.52/src/syntax/trees/StateMachine").StateMachine;
function safeGetLabel(tree) {
return tree.name ? tree.name.value : null;
}
var BreakContinueTransformer = function BreakContinueTransformer(stateAllocator) {
$traceurRuntime.superCall(this, $BreakContinueTransformer.prototype, "constructor", []);
this.transformBreaks_ = true;
this.stateAllocator_ = stateAllocator;
};
var $BreakContinueTransformer = BreakContinueTransformer;
($traceurRuntime.createClass)(BreakContinueTransformer, {
allocateState_: function() {
return this.stateAllocator_.allocateState();
},
stateToStateMachine_: function(newState) {
var fallThroughState = this.allocateState_();
return new StateMachine(newState.id, fallThroughState, [newState], []);
},
transformBreakStatement: function(tree) {
return this.transformBreaks_ || tree.name ? this.stateToStateMachine_(new BreakState(this.allocateState_(), safeGetLabel(tree))) : tree;
},
transformContinueStatement: function(tree) {
return this.stateToStateMachine_(new ContinueState(this.allocateState_(), safeGetLabel(tree)));
},
transformDoWhileStatement: function(tree) {
return tree;
},
transformForOfStatement: function(tree) {
return tree;
},
transformForStatement: function(tree) {
return tree;
},
transformFunctionDeclaration: function(tree) {
return tree;
},
transformFunctionExpression: function(tree) {
return tree;
},
transformStateMachine: function(tree) {
return tree;
},
transformSwitchStatement: function(tree) {
var oldState = this.transformBreaks_;
this.transformBreaks_ = false;
var result = $traceurRuntime.superCall(this, $BreakContinueTransformer.prototype, "transformSwitchStatement", [tree]);
this.transformBreaks_ = oldState;
return result;
},
transformWhileStatement: function(tree) {
return tree;
}
}, {}, ParseTreeTransformer);
return {get BreakContinueTransformer() {
return BreakContinueTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/CatchState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/CatchState";
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var TryState = System.get("traceur@0.0.52/src/codegeneration/generator/TryState").TryState;
var CatchState = function CatchState(identifier, catchState, fallThroughState, allStates, nestedTrys) {
$traceurRuntime.superCall(this, $CatchState.prototype, "constructor", [TryState.Kind.CATCH, allStates, nestedTrys]);
this.identifier = identifier;
this.catchState = catchState;
this.fallThroughState = fallThroughState;
};
var $CatchState = CatchState;
($traceurRuntime.createClass)(CatchState, {replaceState: function(oldState, newState) {
return new $CatchState(this.identifier, State.replaceStateId(this.catchState, oldState, newState), State.replaceStateId(this.fallThroughState, oldState, newState), this.replaceAllStates(oldState, newState), this.replaceNestedTrys(oldState, newState));
}}, {}, TryState);
return {get CatchState() {
return CatchState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/ConditionalState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/ConditionalState";
var $__436 = Object.freeze(Object.defineProperties(["$ctx.state = (", ") ? ", " : ", ";\n break"], {raw: {value: Object.freeze(["$ctx.state = (", ") ? ", " : ", ";\n break"])}}));
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var $__438 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createBlock = $__438.createBlock,
createIfStatement = $__438.createIfStatement;
var parseStatements = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatements;
var ConditionalState = function ConditionalState(id, ifState, elseState, condition) {
$traceurRuntime.superCall(this, $ConditionalState.prototype, "constructor", [id]);
this.ifState = ifState;
this.elseState = elseState;
this.condition = condition;
};
var $ConditionalState = ConditionalState;
($traceurRuntime.createClass)(ConditionalState, {
replaceState: function(oldState, newState) {
return new $ConditionalState(State.replaceStateId(this.id, oldState, newState), State.replaceStateId(this.ifState, oldState, newState), State.replaceStateId(this.elseState, oldState, newState), this.condition);
},
transform: function(enclosingFinally, machineEndState, reporter) {
if (State.isFinallyExit(enclosingFinally, this.ifState) || State.isFinallyExit(enclosingFinally, this.elseState)) {
return [createIfStatement(this.condition, createBlock(State.generateJump(enclosingFinally, this.ifState)), createBlock(State.generateJump(enclosingFinally, this.elseState)))];
}
return parseStatements($__436, this.condition, this.ifState, this.elseState);
}
}, {}, State);
return {get ConditionalState() {
return ConditionalState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/FinallyFallThroughState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/FinallyFallThroughState";
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var FinallyFallThroughState = function FinallyFallThroughState() {
$traceurRuntime.defaultSuperCall(this, $FinallyFallThroughState.prototype, arguments);
};
var $FinallyFallThroughState = FinallyFallThroughState;
($traceurRuntime.createClass)(FinallyFallThroughState, {
replaceState: function(oldState, newState) {
return new $FinallyFallThroughState(State.replaceStateId(this.id, oldState, newState));
},
transformMachineState: function(enclosingFinally, machineEndState, reporter) {
return null;
},
transform: function(enclosingFinally, machineEndState, reporter) {
throw new Error('these are generated in addFinallyFallThroughDispatches');
}
}, {}, State);
return {get FinallyFallThroughState() {
return FinallyFallThroughState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/FinallyState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/FinallyState";
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var TryState = System.get("traceur@0.0.52/src/codegeneration/generator/TryState").TryState;
var FinallyState = function FinallyState(finallyState, fallThroughState, allStates, nestedTrys) {
$traceurRuntime.superCall(this, $FinallyState.prototype, "constructor", [TryState.Kind.FINALLY, allStates, nestedTrys]);
this.finallyState = finallyState;
this.fallThroughState = fallThroughState;
};
var $FinallyState = FinallyState;
($traceurRuntime.createClass)(FinallyState, {replaceState: function(oldState, newState) {
return new $FinallyState(State.replaceStateId(this.finallyState, oldState, newState), State.replaceStateId(this.fallThroughState, oldState, newState), this.replaceAllStates(oldState, newState), this.replaceNestedTrys(oldState, newState));
}}, {}, TryState);
return {get FinallyState() {
return FinallyState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/StateAllocator", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/StateAllocator";
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var StateAllocator = function StateAllocator() {
this.nextState_ = State.START_STATE + 1;
};
($traceurRuntime.createClass)(StateAllocator, {allocateState: function() {
return this.nextState_++;
}}, {});
return {get StateAllocator() {
return StateAllocator;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/SwitchState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/SwitchState";
var $__448 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
CaseClause = $__448.CaseClause,
DefaultClause = $__448.DefaultClause,
SwitchStatement = $__448.SwitchStatement;
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var createBreakStatement = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createBreakStatement;
var SwitchClause = function SwitchClause(first, second) {
this.first = first;
this.second = second;
};
($traceurRuntime.createClass)(SwitchClause, {}, {});
var SwitchState = function SwitchState(id, expression, clauses) {
$traceurRuntime.superCall(this, $SwitchState.prototype, "constructor", [id]);
this.expression = expression;
this.clauses = clauses;
};
var $SwitchState = SwitchState;
($traceurRuntime.createClass)(SwitchState, {
replaceState: function(oldState, newState) {
var clauses = this.clauses.map((function(clause) {
return new SwitchClause(clause.first, State.replaceStateId(clause.second, oldState, newState));
}));
return new $SwitchState(State.replaceStateId(this.id, oldState, newState), this.expression, clauses);
},
transform: function(enclosingFinally, machineEndState, reporter) {
var clauses = [];
for (var i = 0; i < this.clauses.length; i++) {
var clause = this.clauses[i];
if (clause.first == null) {
clauses.push(new DefaultClause(null, State.generateJump(enclosingFinally, clause.second)));
} else {
clauses.push(new CaseClause(null, clause.first, State.generateJump(enclosingFinally, clause.second)));
}
}
return [new SwitchStatement(null, this.expression, clauses), createBreakStatement()];
}
}, {}, State);
return {
get SwitchClause() {
return SwitchClause;
},
get SwitchState() {
return SwitchState;
}
};
});
System.register("traceur@0.0.52/src/codegeneration/generator/CPSTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/CPSTransformer";
var $__452 = Object.freeze(Object.defineProperties(["$ctx.pushTry(\n ", ",\n ", ");"], {raw: {value: Object.freeze(["$ctx.pushTry(\n ", ",\n ", ");"])}})),
$__453 = Object.freeze(Object.defineProperties(["$ctx.popTry();"], {raw: {value: Object.freeze(["$ctx.popTry();"])}})),
$__454 = Object.freeze(Object.defineProperties(["\n $ctx.popTry();\n ", " = $ctx.storedException;"], {raw: {value: Object.freeze(["\n $ctx.popTry();\n ", " = $ctx.storedException;"])}})),
$__455 = Object.freeze(Object.defineProperties(["$ctx.popTry();"], {raw: {value: Object.freeze(["$ctx.popTry();"])}})),
$__456 = Object.freeze(Object.defineProperties(["function($ctx) {\n while (true) ", "\n }"], {raw: {value: Object.freeze(["function($ctx) {\n while (true) ", "\n }"])}})),
$__457 = Object.freeze(Object.defineProperties(["var $arguments = arguments;"], {raw: {value: Object.freeze(["var $arguments = arguments;"])}})),
$__458 = Object.freeze(Object.defineProperties(["return ", "(\n ", ",\n ", ", this);"], {raw: {value: Object.freeze(["return ", "(\n ", ",\n ", ", this);"])}})),
$__459 = Object.freeze(Object.defineProperties(["return ", "(\n ", ", this);"], {raw: {value: Object.freeze(["return ", "(\n ", ", this);"])}})),
$__460 = Object.freeze(Object.defineProperties(["return $ctx.end()"], {raw: {value: Object.freeze(["return $ctx.end()"])}})),
$__461 = Object.freeze(Object.defineProperties(["\n $ctx.state = $ctx.finallyFallThrough;\n $ctx.finallyFallThrough = ", ";\n break;"], {raw: {value: Object.freeze(["\n $ctx.state = $ctx.finallyFallThrough;\n $ctx.finallyFallThrough = ", ";\n break;"])}})),
$__462 = Object.freeze(Object.defineProperties(["\n $ctx.state = $ctx.finallyFallThrough;\n break;"], {raw: {value: Object.freeze(["\n $ctx.state = $ctx.finallyFallThrough;\n break;"])}}));
var AlphaRenamer = System.get("traceur@0.0.52/src/codegeneration/AlphaRenamer").AlphaRenamer;
var BreakContinueTransformer = System.get("traceur@0.0.52/src/codegeneration/generator/BreakContinueTransformer").BreakContinueTransformer;
var $__465 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BLOCK = $__465.BLOCK,
CASE_CLAUSE = $__465.CASE_CLAUSE,
CONDITIONAL_EXPRESSION = $__465.CONDITIONAL_EXPRESSION,
EXPRESSION_STATEMENT = $__465.EXPRESSION_STATEMENT,
PAREN_EXPRESSION = $__465.PAREN_EXPRESSION,
STATE_MACHINE = $__465.STATE_MACHINE;
var $__466 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AnonBlock = $__466.AnonBlock,
Block = $__466.Block,
CaseClause = $__466.CaseClause,
IfStatement = $__466.IfStatement,
SwitchStatement = $__466.SwitchStatement;
var CatchState = System.get("traceur@0.0.52/src/codegeneration/generator/CatchState").CatchState;
var ConditionalState = System.get("traceur@0.0.52/src/codegeneration/generator/ConditionalState").ConditionalState;
var ExplodeExpressionTransformer = System.get("traceur@0.0.52/src/codegeneration/ExplodeExpressionTransformer").ExplodeExpressionTransformer;
var FallThroughState = System.get("traceur@0.0.52/src/codegeneration/generator/FallThroughState").FallThroughState;
var FinallyFallThroughState = System.get("traceur@0.0.52/src/codegeneration/generator/FinallyFallThroughState").FinallyFallThroughState;
var FinallyState = System.get("traceur@0.0.52/src/codegeneration/generator/FinallyState").FinallyState;
var FindInFunctionScope = System.get("traceur@0.0.52/src/codegeneration/FindInFunctionScope").FindInFunctionScope;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var $__477 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__477.parseExpression,
parseStatement = $__477.parseStatement,
parseStatements = $__477.parseStatements;
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var StateAllocator = System.get("traceur@0.0.52/src/codegeneration/generator/StateAllocator").StateAllocator;
var StateMachine = System.get("traceur@0.0.52/src/syntax/trees/StateMachine").StateMachine;
var $__481 = System.get("traceur@0.0.52/src/codegeneration/generator/SwitchState"),
SwitchClause = $__481.SwitchClause,
SwitchState = $__481.SwitchState;
var TryState = System.get("traceur@0.0.52/src/codegeneration/generator/TryState").TryState;
var $__483 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createAssignStateStatement = $__483.createAssignStateStatement,
createBreakStatement = $__483.createBreakStatement,
createCaseClause = $__483.createCaseClause,
createDefaultClause = $__483.createDefaultClause,
createExpressionStatement = $__483.createExpressionStatement,
createFunctionBody = $__483.createFunctionBody,
id = $__483.createIdentifierExpression,
createMemberExpression = $__483.createMemberExpression,
createNumberLiteral = $__483.createNumberLiteral,
createSwitchStatement = $__483.createSwitchStatement;
var HoistVariablesTransformer = System.get("traceur@0.0.52/src/codegeneration/HoistVariablesTransformer").default;
var LabelState = function LabelState(name, continueState, fallThroughState) {
this.name = name;
this.continueState = continueState;
this.fallThroughState = fallThroughState;
};
($traceurRuntime.createClass)(LabelState, {}, {});
var NeedsStateMachine = function NeedsStateMachine() {
$traceurRuntime.defaultSuperCall(this, $NeedsStateMachine.prototype, arguments);
};
var $NeedsStateMachine = NeedsStateMachine;
($traceurRuntime.createClass)(NeedsStateMachine, {
visitBreakStatement: function(tree) {
this.found = true;
},
visitContinueStatement: function(tree) {
this.found = true;
},
visitStateMachine: function(tree) {
this.found = true;
},
visitYieldExpression: function(tee) {
this.found = true;
}
}, {}, FindInFunctionScope);
function needsStateMachine(tree) {
var visitor = new NeedsStateMachine(tree);
return visitor.found;
}
var HoistVariables = function HoistVariables() {
$traceurRuntime.defaultSuperCall(this, $HoistVariables.prototype, arguments);
};
var $HoistVariables = HoistVariables;
($traceurRuntime.createClass)(HoistVariables, {prependVariables: function(statements) {
return statements;
}}, {}, HoistVariablesTransformer);
var CPSTransformer = function CPSTransformer(identifierGenerator, reporter) {
$traceurRuntime.superCall(this, $CPSTransformer.prototype, "constructor", [identifierGenerator]);
this.reporter = reporter;
this.stateAllocator_ = new StateAllocator();
this.labelSet_ = Object.create(null);
this.currentLabel_ = null;
this.hoistVariablesTransformer_ = new HoistVariables();
};
var $CPSTransformer = CPSTransformer;
($traceurRuntime.createClass)(CPSTransformer, {
expressionNeedsStateMachine: function(tree) {
return false;
},
allocateState: function() {
return this.stateAllocator_.allocateState();
},
transformBlock: function(tree) {
var labels = this.getLabels_();
var label = this.clearCurrentLabel_();
var transformedTree = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformBlock", [tree]);
var machine = this.transformStatementList_(transformedTree.statements);
if (machine === null)
return transformedTree;
if (label) {
var states = [];
for (var i = 0; i < machine.states.length; i++) {
var state = machine.states[i];
states.push(state.transformBreakOrContinue(labels));
}
machine = new StateMachine(machine.startState, machine.fallThroughState, states, machine.exceptionBlocks);
}
return machine;
},
transformFunctionBody: function(tree) {
this.pushTempScope();
var oldLabels = this.clearLabels_();
var transformedTree = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformFunctionBody", [tree]);
var machine = this.transformStatementList_(transformedTree.statements);
this.restoreLabels_(oldLabels);
this.popTempScope();
return machine == null ? transformedTree : machine;
},
transformStatementList_: function(trees) {
var groups = [];
var newMachine;
for (var i = 0; i < trees.length; i++) {
if (trees[i].type === STATE_MACHINE) {
groups.push(trees[i]);
} else if (needsStateMachine(trees[i])) {
newMachine = this.ensureTransformed_(trees[i]);
groups.push(newMachine);
} else {
var last = groups[groups.length - 1];
if (!(last instanceof Array))
groups.push(last = []);
last.push(trees[i]);
}
}
if (groups.length === 1 && groups[0] instanceof Array)
return null;
var machine = null;
for (var i = 0; i < groups.length; i++) {
if (groups[i] instanceof Array) {
newMachine = this.statementsToStateMachine_(groups[i]);
} else {
newMachine = groups[i];
}
if (i === 0)
machine = newMachine;
else
machine = machine.append(newMachine);
}
return machine;
},
needsStateMachine_: function(statements) {
if (statements instanceof Array) {
for (var i = 0; i < statements.length; i++) {
if (needsStateMachine(statements[i]))
return true;
}
return false;
}
assert(statements instanceof SwitchStatement);
return needsStateMachine(statements);
},
transformCaseClause: function(tree) {
var result = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformCaseClause", [tree]);
var machine = this.transformStatementList_(result.statements);
return machine == null ? result : new CaseClause(null, result.expression, [machine]);
},
transformDoWhileStatement: function(tree) {
var $__489;
var $__487,
$__488;
var labels = this.getLabels_();
var label = this.clearCurrentLabel_();
var machine,
condition,
body;
if (this.expressionNeedsStateMachine(tree.condition)) {
(($__487 = $traceurRuntime.assertObject(this.expressionToStateMachine(tree.condition)), machine = $__487.machine, condition = $__487.expression, $__487));
body = this.transformAny(tree.body);
} else {
var result = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformDoWhileStatement", [tree]);
(($__488 = $traceurRuntime.assertObject(result), condition = $__488.condition, body = $__488.body, $__488));
if (body.type != STATE_MACHINE)
return result;
}
var loopBodyMachine = this.ensureTransformed_(body);
var startState = loopBodyMachine.startState;
var conditionState = loopBodyMachine.fallThroughState;
var fallThroughState = this.allocateState();
var states = [];
this.addLoopBodyStates_(loopBodyMachine, conditionState, fallThroughState, labels, states);
if (machine) {
machine = machine.replaceStartState(conditionState);
conditionState = machine.fallThroughState;
($__489 = states).push.apply($__489, $traceurRuntime.spread(machine.states));
}
states.push(new ConditionalState(conditionState, startState, fallThroughState, condition));
var machine = new StateMachine(startState, fallThroughState, states, loopBodyMachine.exceptionBlocks);
if (label)
machine = machine.replaceStateId(conditionState, label.continueState);
return machine;
},
addLoopBodyStates_: function(loopBodyMachine, continueState, breakState, labels, states) {
for (var i = 0; i < loopBodyMachine.states.length; i++) {
var state = loopBodyMachine.states[i];
states.push(state.transformBreakOrContinue(labels, breakState, continueState));
}
},
transformForStatement: function(tree) {
var $__489,
$__490,
$__491;
var labels = this.getLabels_();
var label = this.clearCurrentLabel_();
var tmp;
var initializer = null,
initializerMachine;
if (tree.initializer) {
if (this.expressionNeedsStateMachine(tree.initializer)) {
tmp = this.expressionToStateMachine(tree.initializer);
initializer = tmp.expression;
initializerMachine = tmp.machine;
} else {
initializer = this.transformAny(tree.initializer);
}
}
var condition = null,
conditionMachine;
if (tree.condition) {
if (this.expressionNeedsStateMachine(tree.condition)) {
tmp = this.expressionToStateMachine(tree.condition);
condition = tmp.expression;
conditionMachine = tmp.machine;
} else {
condition = this.transformAny(tree.condition);
}
}
var increment = null,
incrementMachine;
if (tree.increment) {
if (this.expressionNeedsStateMachine(tree.increment)) {
tmp = this.expressionToStateMachine(tree.increment);
increment = tmp.expression;
incrementMachine = tmp.machine;
} else {
increment = this.transformAny(tree.increment);
}
}
var body = this.transformAny(tree.body);
if (initializer === tree.initializer && condition === tree.condition && increment === tree.increment && body === tree.body) {
return tree;
}
if (!initializerMachine && !conditionMachine && !incrementMachine && body.type !== STATE_MACHINE) {
return new ForStatement(tree.location, initializer, condition, increment, body);
}
var loopBodyMachine = this.ensureTransformed_(body);
var bodyFallThroughId = loopBodyMachine.fallThroughState;
var fallThroughId = this.allocateState();
var startId;
var initializerStartId = initializer ? this.allocateState() : State.INVALID_STATE;
var conditionStartId = increment ? this.allocateState() : bodyFallThroughId;
var loopStartId = loopBodyMachine.startState;
var incrementStartId = bodyFallThroughId;
var states = [];
if (initializer) {
startId = initializerStartId;
var initialiserFallThroughId;
if (condition)
initialiserFallThroughId = conditionStartId;
else
initialiserFallThroughId = loopStartId;
var tmpId = initializerStartId;
if (initializerMachine) {
initializerMachine = initializerMachine.replaceStartState(initializerStartId);
tmpId = initializerMachine.fallThroughState;
($__489 = states).push.apply($__489, $traceurRuntime.spread(initializerMachine.states));
}
states.push(new FallThroughState(tmpId, initialiserFallThroughId, [createExpressionStatement(initializer)]));
}
if (condition) {
if (!initializer)
startId = conditionStartId;
var tmpId = conditionStartId;
if (conditionMachine) {
conditionMachine = conditionMachine.replaceStartState(conditionStartId);
tmpId = conditionMachine.fallThroughState;
($__490 = states).push.apply($__490, $traceurRuntime.spread(conditionMachine.states));
}
states.push(new ConditionalState(tmpId, loopStartId, fallThroughId, condition));
}
if (increment) {
var incrementFallThroughId;
if (condition)
incrementFallThroughId = conditionStartId;
else
incrementFallThroughId = loopStartId;
var tmpId = incrementStartId;
if (incrementMachine) {
incrementMachine = incrementMachine.replaceStartState(incrementStartId);
tmpId = incrementMachine.fallThroughState;
($__491 = states).push.apply($__491, $traceurRuntime.spread(incrementMachine.states));
}
states.push(new FallThroughState(tmpId, incrementFallThroughId, [createExpressionStatement(increment)]));
}
if (!initializer && !condition)
startId = loopStartId;
var continueId;
if (increment)
continueId = incrementStartId;
else if (condition)
continueId = conditionStartId;
else
continueId = loopStartId;
if (!increment && !condition) {
loopBodyMachine = loopBodyMachine.replaceFallThroughState(loopBodyMachine.startState);
}
this.addLoopBodyStates_(loopBodyMachine, continueId, fallThroughId, labels, states);
var machine = new StateMachine(startId, fallThroughId, states, loopBodyMachine.exceptionBlocks);
if (label)
machine = machine.replaceStateId(continueId, label.continueState);
return machine;
},
transformForInStatement: function(tree) {
return tree;
},
transformForOfStatement: function(tree) {
throw new Error('for of statements should be transformed before this pass');
},
transformIfStatement: function(tree) {
var $__489,
$__490,
$__491;
var $__487,
$__488;
var machine,
condition,
ifClause,
elseClause;
if (this.expressionNeedsStateMachine(tree.condition)) {
(($__487 = $traceurRuntime.assertObject(this.expressionToStateMachine(tree.condition)), machine = $__487.machine, condition = $__487.expression, $__487));
ifClause = this.transformAny(tree.ifClause);
elseClause = this.transformAny(tree.elseClause);
} else {
var result = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformIfStatement", [tree]);
(($__488 = $traceurRuntime.assertObject(result), condition = $__488.condition, ifClause = $__488.ifClause, elseClause = $__488.elseClause, $__488));
if (ifClause.type !== STATE_MACHINE && (elseClause === null || elseClause.type !== STATE_MACHINE)) {
return result;
}
}
ifClause = this.ensureTransformed_(ifClause);
elseClause = this.ensureTransformed_(elseClause);
var startState = this.allocateState();
var fallThroughState = ifClause.fallThroughState;
var ifState = ifClause.startState;
var elseState = elseClause == null ? fallThroughState : elseClause.startState;
var states = [];
var exceptionBlocks = [];
states.push(new ConditionalState(startState, ifState, elseState, condition));
($__489 = states).push.apply($__489, $traceurRuntime.spread(ifClause.states));
($__490 = exceptionBlocks).push.apply($__490, $traceurRuntime.spread(ifClause.exceptionBlocks));
if (elseClause != null) {
this.replaceAndAddStates_(elseClause.states, elseClause.fallThroughState, fallThroughState, states);
($__491 = exceptionBlocks).push.apply($__491, $traceurRuntime.spread(State.replaceAllStates(elseClause.exceptionBlocks, elseClause.fallThroughState, fallThroughState)));
}
var ifMachine = new StateMachine(startState, fallThroughState, states, exceptionBlocks);
if (machine)
ifMachine = machine.append(ifMachine);
return ifMachine;
},
removeEmptyStates: function(oldStates) {
var emptyStates = [],
newStates = [];
for (var i = 0; i < oldStates.length; i++) {
if (oldStates[i] instanceof FallThroughState && oldStates[i].statements.length === 0) {
emptyStates.push(oldStates[i]);
} else {
newStates.push(oldStates[i]);
}
}
for (i = 0; i < newStates.length; i++) {
newStates[i] = emptyStates.reduce((function(state, $__487) {
var $__488 = $traceurRuntime.assertObject($__487),
id = $__488.id,
fallThroughState = $__488.fallThroughState;
return state.replaceState(id, fallThroughState);
}), newStates[i]);
}
return newStates;
},
replaceAndAddStates_: function(oldStates, oldState, newState, newStates) {
for (var i = 0; i < oldStates.length; i++) {
newStates.push(oldStates[i].replaceState(oldState, newState));
}
},
transformLabelledStatement: function(tree) {
var startState = this.allocateState();
var continueState = this.allocateState();
var fallThroughState = this.allocateState();
var label = new LabelState(tree.name.value, continueState, fallThroughState);
var oldLabels = this.addLabel_(label);
this.currentLabel_ = label;
var result = this.transformAny(tree.statement);
if (result === tree.statement) {
result = tree;
} else if (result.type === STATE_MACHINE) {
result = result.replaceStartState(startState);
result = result.replaceFallThroughState(fallThroughState);
}
this.restoreLabels_(oldLabels);
return result;
},
getLabels_: function() {
return this.labelSet_;
},
restoreLabels_: function(oldLabels) {
this.labelSet_ = oldLabels;
},
addLabel_: function(label) {
var oldLabels = this.labelSet_;
var labelSet = Object.create(null);
for (var k in this.labelSet_) {
labelSet[k] = this.labelSet_[k];
}
labelSet[label.name] = label;
this.labelSet_ = labelSet;
return oldLabels;
},
clearLabels_: function() {
var result = this.labelSet_;
this.labelSet_ = Object.create(null);
return result;
},
clearCurrentLabel_: function() {
var result = this.currentLabel_;
this.currentLabel_ = null;
return result;
},
transformSwitchStatement: function(tree) {
var $__487,
$__488;
var labels = this.getLabels_();
var expression,
machine,
caseClauses;
if (this.expressionNeedsStateMachine(tree.expression)) {
(($__487 = $traceurRuntime.assertObject(this.expressionToStateMachine(tree.expression)), expression = $__487.expression, machine = $__487.machine, $__487));
caseClauses = this.transformList(tree.caseClauses);
} else {
var result = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformSwitchStatement", [tree]);
if (!needsStateMachine(result))
return result;
(($__488 = $traceurRuntime.assertObject(result), expression = $__488.expression, caseClauses = $__488.caseClauses, $__488));
}
var startState = this.allocateState();
var fallThroughState = this.allocateState();
var nextState = fallThroughState;
var states = [];
var clauses = [];
var tryStates = [];
var hasDefault = false;
for (var index = caseClauses.length - 1; index >= 0; index--) {
var clause = caseClauses[index];
if (clause.type == CASE_CLAUSE) {
var caseClause = clause;
nextState = this.addSwitchClauseStates_(nextState, fallThroughState, labels, caseClause.statements, states, tryStates);
clauses.push(new SwitchClause(caseClause.expression, nextState));
} else {
hasDefault = true;
var defaultClause = clause;
nextState = this.addSwitchClauseStates_(nextState, fallThroughState, labels, defaultClause.statements, states, tryStates);
clauses.push(new SwitchClause(null, nextState));
}
}
if (!hasDefault) {
clauses.push(new SwitchClause(null, fallThroughState));
}
states.push(new SwitchState(startState, expression, clauses.reverse()));
var switchMachine = new StateMachine(startState, fallThroughState, states.reverse(), tryStates);
if (machine)
switchMachine = machine.append(switchMachine);
return switchMachine;
},
addSwitchClauseStates_: function(nextState, fallThroughState, labels, statements, states, tryStates) {
var $__489;
var machine = this.ensureTransformedList_(statements);
for (var i = 0; i < machine.states.length; i++) {
var state = machine.states[i];
var transformedState = state.transformBreak(labels, fallThroughState);
states.push(transformedState.replaceState(machine.fallThroughState, nextState));
}
($__489 = tryStates).push.apply($__489, $traceurRuntime.spread(machine.exceptionBlocks));
return machine.startState;
},
transformTryStatement: function(tree) {
var result = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformTryStatement", [tree]);
var $__487 = $traceurRuntime.assertObject(result),
body = $__487.body,
catchBlock = $__487.catchBlock,
finallyBlock = $__487.finallyBlock;
if (body.type != STATE_MACHINE && (catchBlock == null || catchBlock.catchBody.type != STATE_MACHINE) && (finallyBlock == null || finallyBlock.block.type != STATE_MACHINE)) {
return result;
}
var outerCatchState = this.allocateState();
var outerFinallyState = this.allocateState();
var pushTryState = this.statementToStateMachine_(parseStatement($__452, (catchBlock && outerCatchState), (finallyBlock && outerFinallyState)));
var tryMachine = this.ensureTransformed_(body);
tryMachine = pushTryState.append(tryMachine);
if (catchBlock !== null) {
var popTry = this.statementToStateMachine_(parseStatement($__453));
tryMachine = tryMachine.append(popTry);
var exceptionName = catchBlock.binding.identifierToken.value;
var catchMachine = this.ensureTransformed_(catchBlock.catchBody);
var catchStart = this.allocateState();
this.addMachineVariable(exceptionName);
var states = $traceurRuntime.spread(tryMachine.states, [new FallThroughState(catchStart, catchMachine.startState, parseStatements($__454, id(exceptionName)))]);
this.replaceAndAddStates_(catchMachine.states, catchMachine.fallThroughState, tryMachine.fallThroughState, states);
tryMachine = new StateMachine(tryMachine.startState, tryMachine.fallThroughState, states, [new CatchState(exceptionName, catchStart, tryMachine.fallThroughState, tryMachine.getAllStateIDs(), tryMachine.exceptionBlocks)]);
tryMachine = tryMachine.replaceStateId(catchStart, outerCatchState);
}
if (finallyBlock != null) {
var finallyMachine = this.ensureTransformed_(finallyBlock.block);
var popTry = this.statementToStateMachine_(parseStatement($__455));
finallyMachine = popTry.append(finallyMachine);
var states = $traceurRuntime.spread(tryMachine.states, finallyMachine.states, [new FinallyFallThroughState(finallyMachine.fallThroughState)]);
tryMachine = new StateMachine(tryMachine.startState, tryMachine.fallThroughState, states, [new FinallyState(finallyMachine.startState, finallyMachine.fallThroughState, tryMachine.getAllStateIDs(), tryMachine.exceptionBlocks)]);
tryMachine = tryMachine.replaceStateId(finallyMachine.startState, outerFinallyState);
}
return tryMachine;
},
transformWhileStatement: function(tree) {
var $__489;
var $__487,
$__488;
var labels = this.getLabels_();
var label = this.clearCurrentLabel_();
var condition,
machine,
body;
if (this.expressionNeedsStateMachine(tree.condition)) {
(($__487 = $traceurRuntime.assertObject(this.expressionToStateMachine(tree.condition)), machine = $__487.machine, condition = $__487.expression, $__487));
body = this.transformAny(tree.body);
} else {
var result = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformWhileStatement", [tree]);
(($__488 = $traceurRuntime.assertObject(result), condition = $__488.condition, body = $__488.body, $__488));
if (body.type !== STATE_MACHINE)
return result;
}
var loopBodyMachine = this.ensureTransformed_(body);
var startState = loopBodyMachine.fallThroughState;
var fallThroughState = this.allocateState();
var states = [];
var conditionStart = startState;
if (machine) {
machine = machine.replaceStartState(startState);
conditionStart = machine.fallThroughState;
($__489 = states).push.apply($__489, $traceurRuntime.spread(machine.states));
}
states.push(new ConditionalState(conditionStart, loopBodyMachine.startState, fallThroughState, condition));
this.addLoopBodyStates_(loopBodyMachine, startState, fallThroughState, labels, states);
var machine = new StateMachine(startState, fallThroughState, states, loopBodyMachine.exceptionBlocks);
if (label)
machine = machine.replaceStateId(startState, label.continueState);
return machine;
},
transformWithStatement: function(tree) {
var result = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformWithStatement", [tree]);
if (result.body.type != STATE_MACHINE) {
return result;
}
throw new Error('Unreachable - with statement not allowed in strict mode/harmony');
},
generateMachineInnerFunction: function(machine) {
var enclosingFinallyState = machine.getEnclosingFinallyMap();
var SwitchStatement = createSwitchStatement(createMemberExpression('$ctx', 'state'), this.transformMachineStates(machine, State.END_STATE, State.RETHROW_STATE, enclosingFinallyState));
return parseExpression($__456, SwitchStatement);
},
addTempVar: function() {
var name = this.getTempIdentifier();
this.addMachineVariable(name);
return name;
},
addMachineVariable: function(name) {
this.hoistVariablesTransformer_.addVariable(name);
},
transformCpsFunctionBody: function(tree, runtimeMethod) {
var functionRef = arguments[2];
var alphaRenamedTree = AlphaRenamer.rename(tree, 'arguments', '$arguments');
var hasArguments = alphaRenamedTree !== tree;
var hoistedTree = this.hoistVariablesTransformer_.transformAny(alphaRenamedTree);
var maybeMachine = this.transformAny(hoistedTree);
if (this.reporter.hadError())
return tree;
var machine;
if (maybeMachine.type !== STATE_MACHINE) {
machine = this.statementsToStateMachine_(maybeMachine.statements);
} else {
machine = new StateMachine(maybeMachine.startState, maybeMachine.fallThroughState, this.removeEmptyStates(maybeMachine.states), maybeMachine.exceptionBlocks);
}
machine = machine.replaceFallThroughState(State.END_STATE).replaceStartState(State.START_STATE);
var statements = [];
if (this.hoistVariablesTransformer_.hasVariables())
statements.push(this.hoistVariablesTransformer_.getVariableStatement());
if (hasArguments)
statements.push(parseStatement($__457));
if (functionRef) {
statements.push(parseStatement($__458, runtimeMethod, this.generateMachineInnerFunction(machine), functionRef));
} else {
statements.push(parseStatement($__459, runtimeMethod, this.generateMachineInnerFunction(machine)));
}
return createFunctionBody(statements);
},
transformFunctionDeclaration: function(tree) {
return tree;
},
transformFunctionExpression: function(tree) {
return tree;
},
transformGetAccessor: function(tree) {
return tree;
},
transformSetAccessor: function(tree) {
return tree;
},
transformArrowFunctionExpression: function(tree) {
return tree;
},
transformStateMachine: function(tree) {
return tree;
},
statementToStateMachine_: function(statement) {
var statements;
if (statement.type === BLOCK)
statements = statement.statements;
else
statements = [statement];
return this.statementsToStateMachine_(statements);
},
statementsToStateMachine_: function(statements) {
var startState = this.allocateState();
var fallThroughState = this.allocateState();
return this.stateToStateMachine_(new FallThroughState(startState, fallThroughState, statements), fallThroughState);
},
stateToStateMachine_: function(newState, fallThroughState) {
return new StateMachine(newState.id, fallThroughState, [newState], []);
},
transformMachineStates: function(machine, machineEndState, rethrowState, enclosingFinallyState) {
var cases = [];
for (var i = 0; i < machine.states.length; i++) {
var state = machine.states[i];
var stateCase = state.transformMachineState(enclosingFinallyState[state.id], machineEndState, this.reporter);
if (stateCase != null) {
cases.push(stateCase);
}
}
this.addFinallyFallThroughDispatches(null, machine.exceptionBlocks, cases);
cases.push(createDefaultClause(parseStatements($__460)));
return cases;
},
addFinallyFallThroughDispatches: function(enclosingFinallyState, tryStates, cases) {
for (var i = 0; i < tryStates.length; i++) {
var tryState = tryStates[i];
if (tryState.kind == TryState.Kind.FINALLY) {
var finallyState = tryState;
if (enclosingFinallyState != null) {
var caseClauses = [];
var index = 0;
for (var j = 0; j < enclosingFinallyState.tryStates.length; j++) {
var destination = enclosingFinallyState.tryStates[j];
index++;
var statements;
if (index < enclosingFinallyState.tryStates.length) {
statements = [];
} else {
statements = parseStatements($__461, State.INVALID_STATE);
}
caseClauses.push(createCaseClause(createNumberLiteral(destination), statements));
}
caseClauses.push(createDefaultClause([createAssignStateStatement(enclosingFinallyState.finallyState), createBreakStatement()]));
cases.push(createCaseClause(createNumberLiteral(finallyState.fallThroughState), [createSwitchStatement(createMemberExpression('$ctx', 'finallyFallThrough'), caseClauses), createBreakStatement()]));
} else {
cases.push(createCaseClause(createNumberLiteral(finallyState.fallThroughState), parseStatements($__462)));
}
this.addFinallyFallThroughDispatches(finallyState, finallyState.nestedTrys, cases);
} else {
this.addFinallyFallThroughDispatches(enclosingFinallyState, tryState.nestedTrys, cases);
}
}
},
transformVariableDeclarationList: function(tree) {
this.reporter.reportError(tree.location && tree.location.start, 'Traceur: const/let declarations in a block containing a yield are ' + 'not yet implemented');
return tree;
},
maybeTransformStatement_: function(maybeTransformedStatement) {
var breakContinueTransformed = new BreakContinueTransformer(this.stateAllocator_).transformAny(maybeTransformedStatement);
if (breakContinueTransformed != maybeTransformedStatement) {
breakContinueTransformed = this.transformAny(breakContinueTransformed);
}
return breakContinueTransformed;
},
ensureTransformed_: function(statement) {
if (statement == null) {
return null;
}
var maybeTransformed = this.maybeTransformStatement_(statement);
return maybeTransformed.type == STATE_MACHINE ? maybeTransformed : this.statementToStateMachine_(maybeTransformed);
},
ensureTransformedList_: function(statements) {
var maybeTransformedStatements = [];
var foundMachine = false;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
var maybeTransformedStatement = this.maybeTransformStatement_(statement);
maybeTransformedStatements.push(maybeTransformedStatement);
if (maybeTransformedStatement.type == STATE_MACHINE) {
foundMachine = true;
}
}
if (!foundMachine) {
return this.statementsToStateMachine_(statements);
}
return this.transformStatementList_(maybeTransformedStatements);
},
expressionToStateMachine: function(tree) {
var commaExpression = new ExplodeExpressionTransformer(this).transformAny(tree);
var statements = $traceurRuntime.assertObject(new NormalizeCommaExpressionToStatementTransformer().transformAny(commaExpression)).statements;
var lastStatement = statements.pop();
assert(lastStatement.type === EXPRESSION_STATEMENT);
var expression = lastStatement.expression;
statements = $traceurRuntime.superCall(this, $CPSTransformer.prototype, "transformList", [statements]);
var machine = this.transformStatementList_(statements);
return {
expression: expression,
machine: machine
};
}
}, {}, TempVarTransformer);
var NormalizeCommaExpressionToStatementTransformer = function NormalizeCommaExpressionToStatementTransformer() {
$traceurRuntime.defaultSuperCall(this, $NormalizeCommaExpressionToStatementTransformer.prototype, arguments);
};
var $NormalizeCommaExpressionToStatementTransformer = NormalizeCommaExpressionToStatementTransformer;
($traceurRuntime.createClass)(NormalizeCommaExpressionToStatementTransformer, {
transformCommaExpression: function(tree) {
var $__485 = this;
var statements = tree.expressions.map((function(expr) {
if (expr.type === CONDITIONAL_EXPRESSION)
return $__485.transformAny(expr);
return createExpressionStatement(expr);
}));
return new AnonBlock(tree.location, statements);
},
transformConditionalExpression: function(tree) {
var ifBlock = this.transformAny(tree.left);
var elseBlock = this.transformAny(tree.right);
return new IfStatement(tree.location, tree.condition, anonBlockToBlock(ifBlock), anonBlockToBlock(elseBlock));
}
}, {}, ParseTreeTransformer);
function anonBlockToBlock(tree) {
if (tree.type === PAREN_EXPRESSION)
return anonBlockToBlock(tree.expression);
return new Block(tree.location, tree.statements);
}
return {get CPSTransformer() {
return CPSTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/EndState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/EndState";
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var EndState = function EndState() {
$traceurRuntime.defaultSuperCall(this, $EndState.prototype, arguments);
};
var $EndState = EndState;
($traceurRuntime.createClass)(EndState, {
replaceState: function(oldState, newState) {
return new $EndState(State.replaceStateId(this.id, oldState, newState));
},
transform: function(enclosingFinally, machineEndState, reporter) {
return State.generateJump(enclosingFinally, machineEndState);
}
}, {}, State);
return {get EndState() {
return EndState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/AsyncTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/AsyncTransformer";
var $__494 = Object.freeze(Object.defineProperties(["$ctx.value"], {raw: {value: Object.freeze(["$ctx.value"])}})),
$__495 = Object.freeze(Object.defineProperties(["$ctx.returnValue = ", ""], {raw: {value: Object.freeze(["$ctx.returnValue = ", ""])}})),
$__496 = Object.freeze(Object.defineProperties(["$ctx.resolve(", ")"], {raw: {value: Object.freeze(["$ctx.resolve(", ")"])}})),
$__497 = Object.freeze(Object.defineProperties(["$traceurRuntime.asyncWrap"], {raw: {value: Object.freeze(["$traceurRuntime.asyncWrap"])}}));
var AwaitState = System.get("traceur@0.0.52/src/codegeneration/generator/AwaitState").AwaitState;
var $__499 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
BinaryExpression = $__499.BinaryExpression,
ExpressionStatement = $__499.ExpressionStatement;
var CPSTransformer = System.get("traceur@0.0.52/src/codegeneration/generator/CPSTransformer").CPSTransformer;
var EndState = System.get("traceur@0.0.52/src/codegeneration/generator/EndState").EndState;
var FallThroughState = System.get("traceur@0.0.52/src/codegeneration/generator/FallThroughState").FallThroughState;
var $__503 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
AWAIT_EXPRESSION = $__503.AWAIT_EXPRESSION,
BINARY_EXPRESSION = $__503.BINARY_EXPRESSION,
STATE_MACHINE = $__503.STATE_MACHINE;
var $__504 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__504.parseExpression,
parseStatement = $__504.parseStatement,
parseStatements = $__504.parseStatements;
var StateMachine = System.get("traceur@0.0.52/src/syntax/trees/StateMachine").StateMachine;
var FindInFunctionScope = System.get("traceur@0.0.52/src/codegeneration/FindInFunctionScope").FindInFunctionScope;
var createUndefinedExpression = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createUndefinedExpression;
function isAwaitAssign(tree) {
return tree.type === BINARY_EXPRESSION && tree.operator.isAssignmentOperator() && tree.right.type === AWAIT_EXPRESSION && tree.left.isLeftHandSideExpression();
}
var AwaitFinder = function AwaitFinder() {
$traceurRuntime.defaultSuperCall(this, $AwaitFinder.prototype, arguments);
};
var $AwaitFinder = AwaitFinder;
($traceurRuntime.createClass)(AwaitFinder, {visitAwaitExpression: function(tree) {
this.found = true;
}}, {}, FindInFunctionScope);
function scopeContainsAwait(tree) {
return new AwaitFinder(tree).found;
}
var AsyncTransformer = function AsyncTransformer() {
$traceurRuntime.defaultSuperCall(this, $AsyncTransformer.prototype, arguments);
};
var $AsyncTransformer = AsyncTransformer;
($traceurRuntime.createClass)(AsyncTransformer, {
expressionNeedsStateMachine: function(tree) {
if (tree === null)
return false;
return scopeContainsAwait(tree);
},
transformExpressionStatement: function(tree) {
var expression = tree.expression;
if (expression.type === AWAIT_EXPRESSION)
return this.transformAwaitExpression_(expression);
if (isAwaitAssign(expression))
return this.transformAwaitAssign_(expression);
if (this.expressionNeedsStateMachine(expression)) {
return this.expressionToStateMachine(expression).machine;
}
return $traceurRuntime.superCall(this, $AsyncTransformer.prototype, "transformExpressionStatement", [tree]);
},
transformAwaitExpression: function(tree) {
throw new Error('Internal error');
},
transformAwaitExpression_: function(tree) {
return this.transformAwait_(tree, tree.expression, null, null);
},
transformAwaitAssign_: function(tree) {
return this.transformAwait_(tree, tree.right.expression, tree.left, tree.operator);
},
transformAwait_: function(tree, inExpression, left, operator) {
var $__509;
var expression,
machine;
if (this.expressionNeedsStateMachine(inExpression)) {
(($__509 = $traceurRuntime.assertObject(this.expressionToStateMachine(inExpression)), expression = $__509.expression, machine = $__509.machine, $__509));
} else {
expression = this.transformAny(inExpression);
}
var createTaskState = this.allocateState();
var callbackState = this.allocateState();
var fallThroughState = this.allocateState();
if (!left)
callbackState = fallThroughState;
var states = [];
var expression = this.transformAny(expression);
states.push(new AwaitState(createTaskState, callbackState, expression));
if (left) {
var statement = new ExpressionStatement(tree.location, new BinaryExpression(tree.location, left, operator, parseExpression($__494)));
var assignment = [statement];
states.push(new FallThroughState(callbackState, fallThroughState, assignment));
}
var awaitMachine = new StateMachine(createTaskState, fallThroughState, states, []);
if (machine) {
awaitMachine = machine.append(awaitMachine);
}
return awaitMachine;
},
transformFinally: function(tree) {
var result = $traceurRuntime.superCall(this, $AsyncTransformer.prototype, "transformFinally", [tree]);
if (result.block.type != STATE_MACHINE) {
return result;
}
this.reporter.reportError(tree.location.start, 'await not permitted within a finally block.');
return result;
},
transformReturnStatement: function(tree) {
var $__509;
var expression,
machine;
if (this.expressionNeedsStateMachine(tree.expression)) {
(($__509 = $traceurRuntime.assertObject(this.expressionToStateMachine(tree.expression)), expression = $__509.expression, machine = $__509.machine, $__509));
} else {
expression = tree.expression || createUndefinedExpression();
}
var startState = this.allocateState();
var endState = this.allocateState();
var completeState = new FallThroughState(startState, endState, parseStatements($__495, expression));
var end = new EndState(endState);
var returnMachine = new StateMachine(startState, this.allocateState(), [completeState, end], []);
if (machine)
returnMachine = machine.append(returnMachine);
return returnMachine;
},
createCompleteTask_: function(result) {
return parseStatement($__496, result);
},
transformAsyncBody: function(tree) {
var runtimeFunction = parseExpression($__497);
return this.transformCpsFunctionBody(tree, runtimeFunction);
}
}, {transformAsyncBody: function(identifierGenerator, reporter, body) {
return new $AsyncTransformer(identifierGenerator, reporter).transformAsyncBody(body);
}}, CPSTransformer);
;
return {get AsyncTransformer() {
return AsyncTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/ForInTransformPass", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/ForInTransformPass";
var $__510 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BLOCK = $__510.BLOCK,
VARIABLE_DECLARATION_LIST = $__510.VARIABLE_DECLARATION_LIST,
IDENTIFIER_EXPRESSION = $__510.IDENTIFIER_EXPRESSION;
var $__511 = System.get("traceur@0.0.52/src/syntax/PredefinedName"),
LENGTH = $__511.LENGTH,
PUSH = $__511.PUSH;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__513 = System.get("traceur@0.0.52/src/syntax/TokenType"),
BANG = $__513.BANG,
IN = $__513.IN,
OPEN_ANGLE = $__513.OPEN_ANGLE,
PLUS_PLUS = $__513.PLUS_PLUS,
VAR = $__513.VAR;
var $__514 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArgumentList = $__514.createArgumentList,
createAssignmentStatement = $__514.createAssignmentStatement,
createBinaryExpression = $__514.createBinaryExpression,
createBlock = $__514.createBlock,
createCallStatement = $__514.createCallStatement,
createContinueStatement = $__514.createContinueStatement,
createEmptyArrayLiteralExpression = $__514.createEmptyArrayLiteralExpression,
createForInStatement = $__514.createForInStatement,
createForStatement = $__514.createForStatement,
createIdentifierExpression = $__514.createIdentifierExpression,
createIfStatement = $__514.createIfStatement,
createMemberExpression = $__514.createMemberExpression,
createMemberLookupExpression = $__514.createMemberLookupExpression,
createNumberLiteral = $__514.createNumberLiteral,
createOperatorToken = $__514.createOperatorToken,
createParenExpression = $__514.createParenExpression,
createPostfixExpression = $__514.createPostfixExpression,
createUnaryExpression = $__514.createUnaryExpression,
createVariableDeclarationList = $__514.createVariableDeclarationList,
createVariableStatement = $__514.createVariableStatement;
var ForInTransformPass = function ForInTransformPass() {
$traceurRuntime.defaultSuperCall(this, $ForInTransformPass.prototype, arguments);
};
var $ForInTransformPass = ForInTransformPass;
($traceurRuntime.createClass)(ForInTransformPass, {transformForInStatement: function(original) {
var $__516,
$__517;
var tree = original;
var bodyStatements = [];
var body = this.transformAny(tree.body);
if (body.type == BLOCK) {
($__516 = bodyStatements).push.apply($__516, $traceurRuntime.spread(body.statements));
} else {
bodyStatements.push(body);
}
var elements = [];
var keys = this.getTempIdentifier();
elements.push(createVariableStatement(VAR, keys, createEmptyArrayLiteralExpression()));
var collection = this.getTempIdentifier();
elements.push(createVariableStatement(VAR, collection, tree.collection));
var p = this.getTempIdentifier();
elements.push(createForInStatement(createVariableDeclarationList(VAR, p, null), createIdentifierExpression(collection), createCallStatement(createMemberExpression(keys, PUSH), createArgumentList([createIdentifierExpression(p)]))));
var i = this.getTempIdentifier();
var lookup = createMemberLookupExpression(createIdentifierExpression(keys), createIdentifierExpression(i));
var originalKey,
assignOriginalKey;
if (tree.initializer.type == VARIABLE_DECLARATION_LIST) {
var decList = tree.initializer;
originalKey = createIdentifierExpression(decList.declarations[0].lvalue);
assignOriginalKey = createVariableStatement(decList.declarationType, originalKey.identifierToken, lookup);
} else if (tree.initializer.type == IDENTIFIER_EXPRESSION) {
originalKey = tree.initializer;
assignOriginalKey = createAssignmentStatement(tree.initializer, lookup);
} else {
throw new Error('Invalid left hand side of for in loop');
}
var innerBlock = [];
innerBlock.push(assignOriginalKey);
innerBlock.push(createIfStatement(createUnaryExpression(createOperatorToken(BANG), createParenExpression(createBinaryExpression(originalKey, createOperatorToken(IN), createIdentifierExpression(collection)))), createContinueStatement(), null));
($__517 = innerBlock).push.apply($__517, $traceurRuntime.spread(bodyStatements));
elements.push(createForStatement(createVariableDeclarationList(VAR, i, createNumberLiteral(0)), createBinaryExpression(createIdentifierExpression(i), createOperatorToken(OPEN_ANGLE), createMemberExpression(keys, LENGTH)), createPostfixExpression(createIdentifierExpression(i), createOperatorToken(PLUS_PLUS)), createBlock(innerBlock)));
return createBlock(elements);
}}, {}, TempVarTransformer);
return {get ForInTransformPass() {
return ForInTransformPass;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/YieldState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/YieldState";
var $__518 = Object.freeze(Object.defineProperties(["return ", ""], {raw: {value: Object.freeze(["return ", ""])}}));
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var parseStatement = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatement;
var YieldState = function YieldState(id, fallThroughState, expression) {
$traceurRuntime.superCall(this, $YieldState.prototype, "constructor", [id]);
this.fallThroughState = fallThroughState;
this.expression = expression;
};
var $YieldState = YieldState;
($traceurRuntime.createClass)(YieldState, {
replaceState: function(oldState, newState) {
return new this.constructor(State.replaceStateId(this.id, oldState, newState), State.replaceStateId(this.fallThroughState, oldState, newState), this.expression);
},
transform: function(enclosingFinally, machineEndState, reporter) {
return $traceurRuntime.spread(State.generateAssignState(enclosingFinally, this.fallThroughState), [parseStatement($__518, this.expression)]);
}
}, {}, State);
return {get YieldState() {
return YieldState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/ReturnState", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/ReturnState";
var $__522 = Object.freeze(Object.defineProperties(["$ctx.returnValue = ", ""], {raw: {value: Object.freeze(["$ctx.returnValue = ", ""])}}));
var $__523 = System.get("traceur@0.0.52/src/semantics/util"),
isUndefined = $__523.isUndefined,
isVoidExpression = $__523.isVoidExpression;
var YieldState = System.get("traceur@0.0.52/src/codegeneration/generator/YieldState").YieldState;
var State = System.get("traceur@0.0.52/src/codegeneration/generator/State").State;
var parseStatement = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatement;
var ReturnState = function ReturnState() {
$traceurRuntime.defaultSuperCall(this, $ReturnState.prototype, arguments);
};
var $ReturnState = ReturnState;
($traceurRuntime.createClass)(ReturnState, {transform: function(enclosingFinally, machineEndState, reporter) {
var $__528;
var e = this.expression;
var statements = [];
if (e && !isUndefined(e) && !isVoidExpression(e))
statements.push(parseStatement($__522, this.expression));
($__528 = statements).push.apply($__528, $traceurRuntime.spread(State.generateJump(enclosingFinally, machineEndState)));
return statements;
}}, {}, YieldState);
return {get ReturnState() {
return ReturnState;
}};
});
System.register("traceur@0.0.52/src/codegeneration/generator/GeneratorTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/generator/GeneratorTransformer";
var $__529 = Object.freeze(Object.defineProperties(["\n ", " = ", "[Symbol.iterator]();\n // received = void 0;\n $ctx.sent = void 0;\n // send = true; // roughly equivalent\n $ctx.action = 'next';\n\n for (;;) {\n ", " = ", "[$ctx.action]($ctx.sentIgnoreThrow);\n if (", ".done) {\n $ctx.sent = ", ".value;\n break;\n }\n ", ";\n }"], {raw: {value: Object.freeze(["\n ", " = ", "[Symbol.iterator]();\n // received = void 0;\n $ctx.sent = void 0;\n // send = true; // roughly equivalent\n $ctx.action = 'next';\n\n for (;;) {\n ", " = ", "[$ctx.action]($ctx.sentIgnoreThrow);\n if (", ".done) {\n $ctx.sent = ", ".value;\n break;\n }\n ", ";\n }"])}})),
$__530 = Object.freeze(Object.defineProperties(["$ctx.sentIgnoreThrow"], {raw: {value: Object.freeze(["$ctx.sentIgnoreThrow"])}})),
$__531 = Object.freeze(Object.defineProperties(["$ctx.sent"], {raw: {value: Object.freeze(["$ctx.sent"])}})),
$__532 = Object.freeze(Object.defineProperties(["$ctx.maybeThrow()"], {raw: {value: Object.freeze(["$ctx.maybeThrow()"])}})),
$__533 = Object.freeze(Object.defineProperties(["$traceurRuntime.createGeneratorInstance"], {raw: {value: Object.freeze(["$traceurRuntime.createGeneratorInstance"])}}));
var CPSTransformer = System.get("traceur@0.0.52/src/codegeneration/generator/CPSTransformer").CPSTransformer;
var $__535 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BINARY_EXPRESSION = $__535.BINARY_EXPRESSION,
YIELD_EXPRESSION = $__535.YIELD_EXPRESSION;
var $__536 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
BinaryExpression = $__536.BinaryExpression,
ExpressionStatement = $__536.ExpressionStatement;
var FindInFunctionScope = System.get("traceur@0.0.52/src/codegeneration/FindInFunctionScope").FindInFunctionScope;
var ReturnState = System.get("traceur@0.0.52/src/codegeneration/generator/ReturnState").ReturnState;
var YieldState = System.get("traceur@0.0.52/src/codegeneration/generator/YieldState").YieldState;
var $__540 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
id = $__540.createIdentifierExpression,
createMemberExpression = $__540.createMemberExpression,
createUndefinedExpression = $__540.createUndefinedExpression,
createYieldStatement = $__540.createYieldStatement;
var $__541 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__541.parseExpression,
parseStatement = $__541.parseStatement,
parseStatements = $__541.parseStatements;
function isYieldAssign(tree) {
return tree.type === BINARY_EXPRESSION && tree.operator.isAssignmentOperator() && tree.right.type === YIELD_EXPRESSION && tree.left.isLeftHandSideExpression();
}
var YieldFinder = function YieldFinder() {
$traceurRuntime.defaultSuperCall(this, $YieldFinder.prototype, arguments);
};
var $YieldFinder = YieldFinder;
($traceurRuntime.createClass)(YieldFinder, {visitYieldExpression: function(tree) {
this.found = true;
}}, {}, FindInFunctionScope);
function scopeContainsYield(tree) {
return new YieldFinder(tree).found;
}
var GeneratorTransformer = function GeneratorTransformer(identifierGenerator, reporter) {
$traceurRuntime.superCall(this, $GeneratorTransformer.prototype, "constructor", [identifierGenerator, reporter]);
this.shouldAppendThrowCloseState_ = true;
};
var $GeneratorTransformer = GeneratorTransformer;
($traceurRuntime.createClass)(GeneratorTransformer, {
expressionNeedsStateMachine: function(tree) {
if (tree === null)
return false;
return scopeContainsYield(tree);
},
transformYieldExpression_: function(tree) {
var $__543;
var expression,
machine;
if (this.expressionNeedsStateMachine(tree.expression)) {
(($__543 = $traceurRuntime.assertObject(this.expressionToStateMachine(tree.expression)), expression = $__543.expression, machine = $__543.machine, $__543));
} else {
expression = this.transformAny(tree.expression);
if (!expression)
expression = createUndefinedExpression();
}
if (tree.isYieldFor)
return this.transformYieldForExpression_(expression, machine);
var startState = this.allocateState();
var fallThroughState = this.allocateState();
var yieldMachine = this.stateToStateMachine_(new YieldState(startState, fallThroughState, this.transformAny(expression)), fallThroughState);
if (machine)
yieldMachine = machine.append(yieldMachine);
if (this.shouldAppendThrowCloseState_)
yieldMachine = yieldMachine.append(this.createThrowCloseState_());
return yieldMachine;
},
transformYieldForExpression_: function(expression) {
var machine = arguments[1];
var gName = this.getTempIdentifier();
this.addMachineVariable(gName);
var g = id(gName);
var nextName = this.getTempIdentifier();
this.addMachineVariable(nextName);
var next = id(nextName);
var statements = parseStatements($__529, g, expression, next, g, next, next, createYieldStatement(createMemberExpression(next, 'value')));
var shouldAppendThrowCloseState = this.shouldAppendThrowCloseState_;
this.shouldAppendThrowCloseState_ = false;
statements = this.transformList(statements);
var yieldMachine = this.transformStatementList_(statements);
this.shouldAppendThrowCloseState_ = shouldAppendThrowCloseState;
if (machine)
yieldMachine = machine.append(yieldMachine);
return yieldMachine;
},
transformYieldExpression: function(tree) {
this.reporter.reportError(tree.location.start, 'Only \'a = yield b\' and \'var a = yield b\' currently supported.');
return tree;
},
transformYieldAssign_: function(tree) {
var shouldAppendThrowCloseState = this.shouldAppendThrowCloseState_;
this.shouldAppendThrowCloseState_ = false;
var machine = this.transformYieldExpression_(tree.right);
var left = this.transformAny(tree.left);
var sentExpression = tree.right.isYieldFor ? parseExpression($__530) : parseExpression($__531);
var statement = new ExpressionStatement(tree.location, new BinaryExpression(tree.location, left, tree.operator, sentExpression));
var assignMachine = this.statementToStateMachine_(statement);
this.shouldAppendThrowCloseState_ = shouldAppendThrowCloseState;
return machine.append(assignMachine);
},
createThrowCloseState_: function() {
return this.statementToStateMachine_(parseStatement($__532));
},
transformExpressionStatement: function(tree) {
var expression = tree.expression;
if (expression.type === YIELD_EXPRESSION)
return this.transformYieldExpression_(expression);
if (isYieldAssign(expression))
return this.transformYieldAssign_(expression);
if (this.expressionNeedsStateMachine(expression)) {
return this.expressionToStateMachine(expression).machine;
}
return $traceurRuntime.superCall(this, $GeneratorTransformer.prototype, "transformExpressionStatement", [tree]);
},
transformAwaitStatement: function(tree) {
this.reporter.reportError(tree.location.start, 'Generator function may not have an await statement.');
return tree;
},
transformReturnStatement: function(tree) {
var $__543;
var expression,
machine;
if (this.expressionNeedsStateMachine(tree.expression))
(($__543 = $traceurRuntime.assertObject(this.expressionToStateMachine(tree.expression)), expression = $__543.expression, machine = $__543.machine, $__543));
else
expression = tree.expression;
var startState = this.allocateState();
var fallThroughState = this.allocateState();
var returnMachine = this.stateToStateMachine_(new ReturnState(startState, fallThroughState, this.transformAny(expression)), fallThroughState);
if (machine)
return machine.append(returnMachine);
return returnMachine;
},
transformGeneratorBody: function(tree, name) {
var runtimeFunction = parseExpression($__533);
return this.transformCpsFunctionBody(tree, runtimeFunction, name);
}
}, {transformGeneratorBody: function(identifierGenerator, reporter, body, name) {
return new $GeneratorTransformer(identifierGenerator, reporter).transformGeneratorBody(body, name);
}}, CPSTransformer);
;
return {get GeneratorTransformer() {
return GeneratorTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/GeneratorTransformPass", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/GeneratorTransformPass";
var $__544 = Object.freeze(Object.defineProperties(["$traceurRuntime.initGeneratorFunction(", ")"], {raw: {value: Object.freeze(["$traceurRuntime.initGeneratorFunction(", ")"])}})),
$__545 = Object.freeze(Object.defineProperties(["var ", " = ", ""], {raw: {value: Object.freeze(["var ", " = ", ""])}})),
$__546 = Object.freeze(Object.defineProperties(["$traceurRuntime.initGeneratorFunction(", ")"], {raw: {value: Object.freeze(["$traceurRuntime.initGeneratorFunction(", ")"])}}));
var ArrowFunctionTransformer = System.get("traceur@0.0.52/src/codegeneration/ArrowFunctionTransformer").ArrowFunctionTransformer;
var AsyncTransformer = System.get("traceur@0.0.52/src/codegeneration/generator/AsyncTransformer").AsyncTransformer;
var ForInTransformPass = System.get("traceur@0.0.52/src/codegeneration/generator/ForInTransformPass").ForInTransformPass;
var GeneratorTransformer = System.get("traceur@0.0.52/src/codegeneration/generator/GeneratorTransformer").GeneratorTransformer;
var $__551 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__551.parseExpression,
parseStatement = $__551.parseStatement;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var FindInFunctionScope = System.get("traceur@0.0.52/src/codegeneration/FindInFunctionScope").FindInFunctionScope;
var $__554 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AnonBlock = $__554.AnonBlock,
FunctionDeclaration = $__554.FunctionDeclaration,
FunctionExpression = $__554.FunctionExpression;
var $__555 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createBindingIdentifier = $__555.createBindingIdentifier,
id = $__555.createIdentifierExpression,
createIdentifierToken = $__555.createIdentifierToken;
var transformOptions = System.get("traceur@0.0.52/src/Options").transformOptions;
var ForInFinder = function ForInFinder() {
$traceurRuntime.defaultSuperCall(this, $ForInFinder.prototype, arguments);
};
var $ForInFinder = ForInFinder;
($traceurRuntime.createClass)(ForInFinder, {visitForInStatement: function(tree) {
this.found = true;
}}, {}, FindInFunctionScope);
function needsTransform(tree) {
return transformOptions.generators && tree.isGenerator() || transformOptions.asyncFunctions && tree.isAsyncFunction();
}
var GeneratorTransformPass = function GeneratorTransformPass(identifierGenerator, reporter) {
$traceurRuntime.superCall(this, $GeneratorTransformPass.prototype, "constructor", [identifierGenerator]);
this.reporter_ = reporter;
this.inBlock_ = false;
};
var $GeneratorTransformPass = GeneratorTransformPass;
($traceurRuntime.createClass)(GeneratorTransformPass, {
transformFunctionDeclaration: function(tree) {
if (!needsTransform(tree))
return $traceurRuntime.superCall(this, $GeneratorTransformPass.prototype, "transformFunctionDeclaration", [tree]);
if (tree.isGenerator())
return this.transformGeneratorDeclaration_(tree);
return this.transformFunction_(tree, FunctionDeclaration, null);
},
transformGeneratorDeclaration_: function(tree) {
var nameIdExpression = id(tree.name.identifierToken);
var setupPrototypeExpression = parseExpression($__544, nameIdExpression);
var tmpVar = id(this.inBlock_ ? this.getTempIdentifier() : this.addTempVar(setupPrototypeExpression));
var funcDecl = this.transformFunction_(tree, FunctionDeclaration, tmpVar);
if (!this.inBlock_)
return funcDecl;
return new AnonBlock(null, [funcDecl, parseStatement($__545, tmpVar, setupPrototypeExpression)]);
},
transformFunctionExpression: function(tree) {
if (!needsTransform(tree))
return $traceurRuntime.superCall(this, $GeneratorTransformPass.prototype, "transformFunctionExpression", [tree]);
if (tree.isGenerator())
return this.transformGeneratorExpression_(tree);
return this.transformFunction_(tree, FunctionExpression, null);
},
transformGeneratorExpression_: function(tree) {
var name;
if (!tree.name) {
name = createIdentifierToken(this.getTempIdentifier());
tree = new FunctionExpression(tree.location, createBindingIdentifier(name), tree.functionKind, tree.parameterList, tree.typeAnnotation, tree.annotations, tree.body);
} else {
name = tree.name.identifierToken;
}
var functionExpression = this.transformFunction_(tree, FunctionExpression, id(name));
return parseExpression($__546, functionExpression);
},
transformFunction_: function(tree, constructor, nameExpression) {
var body = $traceurRuntime.superCall(this, $GeneratorTransformPass.prototype, "transformAny", [tree.body]);
var finder = new ForInFinder(body);
if (finder.found) {
body = new ForInTransformPass(this.identifierGenerator).transformAny(body);
}
if (transformOptions.generators && tree.isGenerator()) {
body = GeneratorTransformer.transformGeneratorBody(this.identifierGenerator, this.reporter_, body, nameExpression);
} else if (transformOptions.asyncFunctions && tree.isAsyncFunction()) {
body = AsyncTransformer.transformAsyncBody(this.identifierGenerator, this.reporter_, body);
}
var functionKind = null;
return new constructor(tree.location, tree.name, functionKind, tree.parameterList, tree.typeAnnotation || null, tree.annotations || null, body);
},
transformArrowFunctionExpression: function(tree) {
if (!tree.isAsyncFunction())
return $traceurRuntime.superCall(this, $GeneratorTransformPass.prototype, "transformArrowFunctionExpression", [tree]);
return this.transformAny(ArrowFunctionTransformer.transform(this, tree));
},
transformBlock: function(tree) {
var inBlock = this.inBlock_;
this.inBlock_ = true;
var rv = $traceurRuntime.superCall(this, $GeneratorTransformPass.prototype, "transformBlock", [tree]);
this.inBlock_ = inBlock;
return rv;
}
}, {}, TempVarTransformer);
return {get GeneratorTransformPass() {
return GeneratorTransformPass;
}};
});
System.register("traceur@0.0.52/src/codegeneration/InlineModuleTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/InlineModuleTransformer";
var VAR = System.get("traceur@0.0.52/src/syntax/TokenType").VAR;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var ModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/ModuleTransformer").ModuleTransformer;
var $__561 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createBindingIdentifier = $__561.createBindingIdentifier,
createEmptyStatement = $__561.createEmptyStatement,
createFunctionBody = $__561.createFunctionBody,
createImmediatelyInvokedFunctionExpression = $__561.createImmediatelyInvokedFunctionExpression,
createScopedExpression = $__561.createScopedExpression,
createVariableStatement = $__561.createVariableStatement;
var globalThis = System.get("traceur@0.0.52/src/codegeneration/globalThis").default;
var scopeContainsThis = System.get("traceur@0.0.52/src/codegeneration/scopeContainsThis").default;
var InlineModuleTransformer = function InlineModuleTransformer() {
$traceurRuntime.defaultSuperCall(this, $InlineModuleTransformer.prototype, arguments);
};
var $InlineModuleTransformer = InlineModuleTransformer;
($traceurRuntime.createClass)(InlineModuleTransformer, {
wrapModule: function(statements) {
assert(this.moduleName);
var idName = this.getTempVarNameForModuleName(this.moduleName);
var body = createFunctionBody(statements);
var moduleExpression;
if (statements.some(scopeContainsThis)) {
moduleExpression = createScopedExpression(body, globalThis());
} else {
moduleExpression = createImmediatelyInvokedFunctionExpression(body);
}
return [createVariableStatement(VAR, idName, moduleExpression)];
},
transformNamedExport: function(tree) {
return createEmptyStatement();
},
transformModuleSpecifier: function(tree) {
return createBindingIdentifier(this.getTempVarNameForModuleSpecifier(tree));
}
}, {}, ModuleTransformer);
return {get InlineModuleTransformer() {
return InlineModuleTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/InstantiateModuleTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/InstantiateModuleTransformer";
var $__565 = Object.freeze(Object.defineProperties(["", " = ", ""], {raw: {value: Object.freeze(["", " = ", ""])}})),
$__566 = Object.freeze(Object.defineProperties(["$__export(", ", ", ")"], {raw: {value: Object.freeze(["$__export(", ", ", ")"])}})),
$__567 = Object.freeze(Object.defineProperties(["($__export(", ", ", " + 1), ", ")"], {raw: {value: Object.freeze(["($__export(", ", ", " + 1), ", ")"])}})),
$__568 = Object.freeze(Object.defineProperties(["$__export(", ", ", ")}"], {raw: {value: Object.freeze(["$__export(", ", ", ")}"])}})),
$__569 = Object.freeze(Object.defineProperties(["System.register(", ", ", ", function($__export) {\n ", "\n });"], {raw: {value: Object.freeze(["System.register(", ", ", ", function($__export) {\n ", "\n });"])}})),
$__570 = Object.freeze(Object.defineProperties(["System.register(", ", function($__export) {\n ", "\n });"], {raw: {value: Object.freeze(["System.register(", ", function($__export) {\n ", "\n });"])}})),
$__571 = Object.freeze(Object.defineProperties(["", " = m.", ";"], {raw: {value: Object.freeze(["", " = m.", ";"])}})),
$__572 = Object.freeze(Object.defineProperties(["$__export(", ", m.", ");"], {raw: {value: Object.freeze(["$__export(", ", m.", ");"])}})),
$__573 = Object.freeze(Object.defineProperties(["", " = m;"], {raw: {value: Object.freeze(["", " = m;"])}})),
$__574 = Object.freeze(Object.defineProperties(["\n Object.keys(m).forEach(function(p) {\n $__export(p, m[p]);\n });\n "], {raw: {value: Object.freeze(["\n Object.keys(m).forEach(function(p) {\n $__export(p, m[p]);\n });\n "])}})),
$__575 = Object.freeze(Object.defineProperties(["function(m) {\n ", "\n }"], {raw: {value: Object.freeze(["function(m) {\n ", "\n }"])}})),
$__576 = Object.freeze(Object.defineProperties(["function(m) {}"], {raw: {value: Object.freeze(["function(m) {}"])}})),
$__577 = Object.freeze(Object.defineProperties(["\n $__export(", ", ", ")\n "], {raw: {value: Object.freeze(["\n $__export(", ", ", ")\n "])}})),
$__578 = Object.freeze(Object.defineProperties(["return {\n setters: ", ",\n execute: ", "\n }"], {raw: {value: Object.freeze(["return {\n setters: ", ",\n execute: ", "\n }"])}})),
$__579 = Object.freeze(Object.defineProperties(["$__export(", ", ", ")"], {raw: {value: Object.freeze(["$__export(", ", ", ")"])}})),
$__580 = Object.freeze(Object.defineProperties(["$__export(", ", ", ")"], {raw: {value: Object.freeze(["$__export(", ", ", ")"])}})),
$__581 = Object.freeze(Object.defineProperties(["var ", " = $__export(", ", ", ");"], {raw: {value: Object.freeze(["var ", " = $__export(", ", ", ");"])}})),
$__582 = Object.freeze(Object.defineProperties(["var ", ";"], {raw: {value: Object.freeze(["var ", ";"])}})),
$__583 = Object.freeze(Object.defineProperties(["$__export('default', ", ");"], {raw: {value: Object.freeze(["$__export('default', ", ");"])}})),
$__584 = Object.freeze(Object.defineProperties(["$__export(", ", ", ");"], {raw: {value: Object.freeze(["$__export(", ", ", ");"])}})),
$__585 = Object.freeze(Object.defineProperties(["var ", ";"], {raw: {value: Object.freeze(["var ", ";"])}}));
var $__586 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
AnonBlock = $__586.AnonBlock,
ArrayLiteralExpression = $__586.ArrayLiteralExpression,
ClassExpression = $__586.ClassExpression,
CommaExpression = $__586.CommaExpression,
ExpressionStatement = $__586.ExpressionStatement;
var $__587 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
FUNCTION_DECLARATION = $__587.FUNCTION_DECLARATION,
IDENTIFIER_EXPRESSION = $__587.IDENTIFIER_EXPRESSION,
IMPORT_SPECIFIER_SET = $__587.IMPORT_SPECIFIER_SET;
var ScopeTransformer = System.get("traceur@0.0.52/src/codegeneration/ScopeTransformer").ScopeTransformer;
var $__589 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
id = $__589.createIdentifierExpression,
createIdentifierToken = $__589.createIdentifierToken,
createVariableStatement = $__589.createVariableStatement,
createVariableDeclaration = $__589.createVariableDeclaration,
createVariableDeclarationList = $__589.createVariableDeclarationList;
var ModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/ModuleTransformer").ModuleTransformer;
var $__591 = System.get("traceur@0.0.52/src/syntax/TokenType"),
MINUS_MINUS = $__591.MINUS_MINUS,
PLUS_PLUS = $__591.PLUS_PLUS,
VAR = $__591.VAR;
var $__592 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__592.parseExpression,
parseStatement = $__592.parseStatement,
parseStatements = $__592.parseStatements;
var HoistVariablesTransformer = System.get("traceur@0.0.52/src/codegeneration/HoistVariablesTransformer").default;
var $__594 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createFunctionExpression = $__594.createFunctionExpression,
createEmptyParameterList = $__594.createEmptyParameterList,
createFunctionBody = $__594.createFunctionBody;
var DeclarationExtractionTransformer = function DeclarationExtractionTransformer() {
$traceurRuntime.superCall(this, $DeclarationExtractionTransformer.prototype, "constructor", []);
this.declarations_ = [];
};
var $DeclarationExtractionTransformer = DeclarationExtractionTransformer;
($traceurRuntime.createClass)(DeclarationExtractionTransformer, {
getDeclarationStatements: function() {
return $traceurRuntime.spread([this.getVariableStatement()], this.declarations_);
},
addDeclaration: function(tree) {
this.declarations_.push(tree);
},
transformFunctionDeclaration: function(tree) {
this.addDeclaration(tree);
return new AnonBlock(null, []);
},
transformClassDeclaration: function(tree) {
this.addVariable(tree.name.identifierToken.value);
tree = new ClassExpression(tree.location, tree.name, tree.superClass, tree.elements, tree.annotations);
return parseStatement($__565, tree.name.identifierToken, tree);
}
}, {}, HoistVariablesTransformer);
var InsertBindingAssignmentTransformer = function InsertBindingAssignmentTransformer(exportName, bindingName) {
$traceurRuntime.superCall(this, $InsertBindingAssignmentTransformer.prototype, "constructor", [bindingName]);
this.bindingName_ = bindingName;
this.exportName_ = exportName;
};
var $InsertBindingAssignmentTransformer = InsertBindingAssignmentTransformer;
($traceurRuntime.createClass)(InsertBindingAssignmentTransformer, {
matchesBindingName_: function(binding) {
return binding.type === IDENTIFIER_EXPRESSION && binding.identifierToken.value == this.bindingName_;
},
transformUnaryExpression: function(tree) {
if (!this.matchesBindingName_(tree.operand))
return $traceurRuntime.superCall(this, $InsertBindingAssignmentTransformer.prototype, "transformUnaryExpression", [tree]);
var operatorType = tree.operator.type;
if (operatorType !== PLUS_PLUS && operatorType !== MINUS_MINUS)
return $traceurRuntime.superCall(this, $InsertBindingAssignmentTransformer.prototype, "transformUnaryExpression", [tree]);
var operand = this.transformAny(tree.operand);
if (operand !== tree.operand)
tree = new UnaryExpression(tree.location, tree.operator, operand);
return parseExpression($__566, this.exportName_, tree);
},
transformPostfixExpression: function(tree) {
tree = $traceurRuntime.superCall(this, $InsertBindingAssignmentTransformer.prototype, "transformPostfixExpression", [tree]);
if (!this.matchesBindingName_(tree.operand))
return tree;
return parseExpression($__567, this.exportName_, tree.operand, tree);
},
transformBinaryExpression: function(tree) {
tree = $traceurRuntime.superCall(this, $InsertBindingAssignmentTransformer.prototype, "transformBinaryExpression", [tree]);
if (!tree.operator.isAssignmentOperator())
return tree;
if (!this.matchesBindingName_(tree.left))
return tree;
return parseExpression($__568, this.exportName_, tree);
}
}, {}, ScopeTransformer);
var InstantiateModuleTransformer = function InstantiateModuleTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $InstantiateModuleTransformer.prototype, "constructor", [identifierGenerator]);
this.inExport_ = false;
this.curDepIndex_ = null;
this.dependencies = [];
this.externalExportBindings = [];
this.importBindings = [];
this.localExportBindings = [];
this.functionDeclarations = [];
this.moduleBindings = [];
this.exportStarBindings = [];
};
var $InstantiateModuleTransformer = InstantiateModuleTransformer;
($traceurRuntime.createClass)(InstantiateModuleTransformer, {
wrapModule: function(statements) {
if (this.moduleName) {
return parseStatements($__569, this.moduleName, this.dependencies, statements);
} else {
return parseStatements($__570, this.dependencies, statements);
}
},
appendExportStatement: function(statements) {
var $__595 = this;
var declarationExtractionTransformer = new DeclarationExtractionTransformer();
this.localExportBindings.forEach((function(binding) {
statements = new InsertBindingAssignmentTransformer(binding.exportName, binding.localName).transformList(statements);
}));
var executionStatements = statements.map((function(statement) {
return declarationExtractionTransformer.transformAny(statement);
}));
var executionFunction = createFunctionExpression(createEmptyParameterList(), createFunctionBody(executionStatements));
var declarationStatements = declarationExtractionTransformer.getDeclarationStatements();
var setterFunctions = this.dependencies.map((function(dep, index) {
var importBindings = $__595.importBindings[index];
var externalExportBindings = $__595.externalExportBindings[index];
var exportStarBinding = $__595.exportStarBindings[index];
var moduleBinding = $__595.moduleBindings[index];
var setterStatements = [];
if (importBindings) {
importBindings.forEach((function(binding) {
setterStatements.push(parseStatement($__571, createIdentifierToken(binding.variableName), binding.exportName));
}));
}
if (externalExportBindings) {
externalExportBindings.forEach((function(binding) {
setterStatements.push(parseStatement($__572, binding.exportName, binding.importName));
}));
}
if (moduleBinding) {
setterStatements.push(parseStatement($__573, id(moduleBinding)));
}
if (exportStarBinding) {
setterStatements = setterStatements.concat(parseStatements($__574));
}
if (setterStatements.length) {
return parseExpression($__575, setterStatements);
} else {
return parseExpression($__576);
}
}));
declarationStatements = declarationStatements.concat(this.functionDeclarations.map((function(binding) {
return parseStatement($__577, binding.exportName, createIdentifierToken(binding.functionName));
})));
declarationStatements.push(parseStatement($__578, new ArrayLiteralExpression(null, setterFunctions), executionFunction));
return declarationStatements;
},
addLocalExportBinding: function(exportName) {
var localName = arguments[1] !== (void 0) ? arguments[1] : exportName;
this.localExportBindings.push({
exportName: exportName,
localName: localName
});
},
addImportBinding: function(depIndex, variableName, exportName) {
this.importBindings[depIndex] = this.importBindings[depIndex] || [];
this.importBindings[depIndex].push({
variableName: variableName,
exportName: exportName
});
},
addExternalExportBinding: function(depIndex, exportName, importName) {
this.externalExportBindings[depIndex] = this.externalExportBindings[depIndex] || [];
this.externalExportBindings[depIndex].push({
exportName: exportName,
importName: importName
});
},
addExportStarBinding: function(depIndex) {
this.exportStarBindings[depIndex] = true;
},
addModuleBinding: function(depIndex, variableName) {
this.moduleBindings[depIndex] = variableName;
},
addExportFunction: function(exportName) {
var functionName = arguments[1] !== (void 0) ? arguments[1] : exportName;
this.functionDeclarations.push({
exportName: exportName,
functionName: functionName
});
},
getOrCreateDependencyIndex: function(moduleSpecifier) {
var name = moduleSpecifier.token.processedValue;
var depIndex = this.dependencies.indexOf(name);
if (depIndex == -1) {
depIndex = this.dependencies.length;
this.dependencies.push(name);
}
return depIndex;
},
transformExportDeclaration: function(tree) {
this.inExport_ = true;
if (tree.declaration.moduleSpecifier) {
this.curDepIndex_ = this.getOrCreateDependencyIndex(tree.declaration.moduleSpecifier);
} else {
this.curDepIndex_ = null;
}
var transformed = this.transformAny(tree.declaration);
this.inExport_ = false;
return transformed;
},
transformVariableStatement: function(tree) {
var $__595 = this;
if (!this.inExport_)
return $traceurRuntime.superCall(this, $InstantiateModuleTransformer.prototype, "transformVariableStatement", [tree]);
this.inExport_ = false;
return createVariableStatement(createVariableDeclarationList(VAR, tree.declarations.declarations.map((function(declaration) {
var varName = declaration.lvalue.identifierToken.value;
var initializer;
$__595.addLocalExportBinding(varName);
if (declaration.initializer)
initializer = parseExpression($__579, varName, $__595.transformAny(declaration.initializer));
else
initializer = parseExpression($__580, varName, id(varName));
return createVariableDeclaration(varName, initializer);
}))));
},
transformExportStar: function(tree) {
this.inExport_ = false;
this.addExportStarBinding(this.curDepIndex_);
return new AnonBlock(null, []);
},
transformClassDeclaration: function(tree) {
if (!this.inExport_)
return $traceurRuntime.superCall(this, $InstantiateModuleTransformer.prototype, "transformClassDeclaration", [tree]);
this.inExport_ = false;
var name = this.transformAny(tree.name);
var superClass = this.transformAny(tree.superClass);
var elements = this.transformList(tree.elements);
var annotations = this.transformList(tree.annotations);
var varName = name.identifierToken.value;
var classExpression = new ClassExpression(tree.location, name, superClass, elements, annotations);
this.addLocalExportBinding(varName);
return parseStatement($__581, varName, varName, classExpression);
},
transformFunctionDeclaration: function(tree) {
if (this.inExport_) {
this.addLocalExportBinding(tree.name.identifierToken.value);
this.addExportFunction(tree.name.identifierToken.value);
this.inExport_ = false;
}
return $traceurRuntime.superCall(this, $InstantiateModuleTransformer.prototype, "transformFunctionDeclaration", [tree]);
},
transformNamedExport: function(tree) {
this.transformAny(tree.moduleSpecifier);
var specifierSet = this.transformAny(tree.specifierSet);
if (this.curDepIndex_ === null) {
return specifierSet;
} else {
return new AnonBlock(null, []);
}
},
transformImportDeclaration: function(tree) {
this.curDepIndex_ = this.getOrCreateDependencyIndex(tree.moduleSpecifier);
var initializer = this.transformAny(tree.moduleSpecifier);
if (!tree.importClause)
return new AnonBlock(null, []);
var importClause = this.transformAny(tree.importClause);
if (tree.importClause.type === IMPORT_SPECIFIER_SET) {
return importClause;
} else {
this.addImportBinding(this.curDepIndex_, tree.importClause.binding.identifierToken.value, 'default');
return parseStatement($__582, tree.importClause.binding.identifierToken.value);
}
return new AnonBlock(null, []);
},
transformImportSpecifierSet: function(tree) {
return createVariableStatement(createVariableDeclarationList(VAR, this.transformList(tree.specifiers)));
},
transformExportDefault: function(tree) {
var expression = this.transformAny(tree.expression);
this.addLocalExportBinding('default');
if (expression.type === FUNCTION_DECLARATION) {
this.addExportFunction('default', expression.name.identifierToken.value);
return expression;
} else {
return parseStatement($__583, expression);
}
},
transformExportSpecifier: function(tree) {
var exportName;
var bindingName;
if (tree.rhs) {
exportName = tree.rhs.value;
bindingName = tree.lhs.value;
} else {
exportName = tree.lhs.value;
bindingName = tree.lhs.value;
}
if (this.curDepIndex_ !== null) {
this.addExternalExportBinding(this.curDepIndex_, exportName, bindingName);
} else {
this.addLocalExportBinding(exportName, bindingName);
return parseExpression($__584, exportName, id(bindingName));
}
},
transformExportSpecifierSet: function(tree) {
var specifiers = this.transformList(tree.specifiers);
return new ExpressionStatement(tree.location, new CommaExpression(tree.location, specifiers.filter((function(specifier) {
return specifier;
}))));
},
transformImportSpecifier: function(tree) {
var importName;
var localBinding;
if (tree.rhs) {
localBinding = tree.rhs;
importName = tree.lhs.value;
} else {
localBinding = tree.lhs;
importName = tree.lhs.value;
}
this.addImportBinding(this.curDepIndex_, localBinding.value, importName);
return createVariableDeclaration(localBinding);
},
transformModuleDeclaration: function(tree) {
this.transformAny(tree.expression);
this.addModuleBinding(this.curDepIndex_, tree.identifier.value);
return parseStatement($__585, tree.identifier.value);
},
transformModuleSpecifier: function(tree) {
this.curDepIndex_ = this.getOrCreateDependencyIndex(tree);
return tree;
}
}, {}, ModuleTransformer);
return {get InstantiateModuleTransformer() {
return InstantiateModuleTransformer;
}};
});
System.register("traceur@0.0.52/src/outputgeneration/ParseTreeWriter", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/outputgeneration/ParseTreeWriter";
var $__597 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BLOCK = $__597.BLOCK,
CLASS_DECLARATION = $__597.CLASS_DECLARATION,
FUNCTION_DECLARATION = $__597.FUNCTION_DECLARATION,
IF_STATEMENT = $__597.IF_STATEMENT,
LITERAL_EXPRESSION = $__597.LITERAL_EXPRESSION,
POSTFIX_EXPRESSION = $__597.POSTFIX_EXPRESSION,
UNARY_EXPRESSION = $__597.UNARY_EXPRESSION;
var ParseTreeVisitor = System.get("traceur@0.0.52/src/syntax/ParseTreeVisitor").ParseTreeVisitor;
var $__599 = System.get("traceur@0.0.52/src/syntax/PredefinedName"),
AS = $__599.AS,
ASYNC = $__599.ASYNC,
AWAIT = $__599.AWAIT,
FROM = $__599.FROM,
GET = $__599.GET,
OF = $__599.OF,
MODULE = $__599.MODULE,
SET = $__599.SET;
var $__600 = System.get("traceur@0.0.52/src/syntax/Scanner"),
isIdentifierPart = $__600.isIdentifierPart,
isWhitespace = $__600.isWhitespace;
var $__601 = System.get("traceur@0.0.52/src/syntax/TokenType"),
ARROW = $__601.ARROW,
AT = $__601.AT,
BACK_QUOTE = $__601.BACK_QUOTE,
BREAK = $__601.BREAK,
CASE = $__601.CASE,
CATCH = $__601.CATCH,
CLASS = $__601.CLASS,
CLOSE_CURLY = $__601.CLOSE_CURLY,
CLOSE_PAREN = $__601.CLOSE_PAREN,
CLOSE_SQUARE = $__601.CLOSE_SQUARE,
COLON = $__601.COLON,
COMMA = $__601.COMMA,
CONTINUE = $__601.CONTINUE,
DEBUGGER = $__601.DEBUGGER,
DEFAULT = $__601.DEFAULT,
DO = $__601.DO,
DOT_DOT_DOT = $__601.DOT_DOT_DOT,
ELSE = $__601.ELSE,
EQUAL = $__601.EQUAL,
EXPORT = $__601.EXPORT,
EXTENDS = $__601.EXTENDS,
FINALLY = $__601.FINALLY,
FOR = $__601.FOR,
FUNCTION = $__601.FUNCTION,
IF = $__601.IF,
IMPORT = $__601.IMPORT,
IN = $__601.IN,
MINUS = $__601.MINUS,
MINUS_MINUS = $__601.MINUS_MINUS,
NEW = $__601.NEW,
NUMBER = $__601.NUMBER,
OPEN_CURLY = $__601.OPEN_CURLY,
OPEN_PAREN = $__601.OPEN_PAREN,
OPEN_SQUARE = $__601.OPEN_SQUARE,
PERIOD = $__601.PERIOD,
PLUS = $__601.PLUS,
PLUS_PLUS = $__601.PLUS_PLUS,
QUESTION = $__601.QUESTION,
RETURN = $__601.RETURN,
SEMI_COLON = $__601.SEMI_COLON,
STAR = $__601.STAR,
STATIC = $__601.STATIC,
SUPER = $__601.SUPER,
SWITCH = $__601.SWITCH,
THIS = $__601.THIS,
THROW = $__601.THROW,
TRY = $__601.TRY,
WHILE = $__601.WHILE,
WITH = $__601.WITH,
YIELD = $__601.YIELD;
var NEW_LINE = '\n';
var LINE_LENGTH = 80;
var ParseTreeWriter = function ParseTreeWriter() {
var $__604,
$__605,
$__606;
var $__603 = $traceurRuntime.assertObject(arguments[0] !== (void 0) ? arguments[0] : {}),
highlighted = ($__604 = $__603.highlighted) === void 0 ? false : $__604,
showLineNumbers = ($__605 = $__603.showLineNumbers) === void 0 ? false : $__605,
prettyPrint = ($__606 = $__603.prettyPrint) === void 0 ? true : $__606;
$traceurRuntime.superCall(this, $ParseTreeWriter.prototype, "constructor", []);
this.highlighted_ = highlighted;
this.showLineNumbers_ = showLineNumbers;
this.prettyPrint_ = prettyPrint;
this.result_ = '';
this.currentLine_ = '';
this.currentLineComment_ = null;
this.indentDepth_ = 0;
this.currentParameterTypeAnnotation_ = null;
};
var $ParseTreeWriter = ParseTreeWriter;
($traceurRuntime.createClass)(ParseTreeWriter, {
toString: function() {
if (this.currentLine_.length > 0) {
this.result_ += this.currentLine_;
this.currentLine_ = '';
}
return this.result_;
},
visitAny: function(tree) {
if (!tree) {
return;
}
if (tree === this.highlighted_) {
this.write_('\x1B[41m');
}
if (tree.location !== null && tree.location.start !== null && this.showLineNumbers_) {
var line = tree.location.start.line + 1;
var column = tree.location.start.column;
this.currentLineComment_ = ("Line: " + line + "." + column);
}
$traceurRuntime.superCall(this, $ParseTreeWriter.prototype, "visitAny", [tree]);
if (tree === this.highlighted_) {
this.write_('\x1B[0m');
}
},
visitAnnotation: function(tree) {
this.write_(AT);
this.visitAny(tree.name);
if (tree.args !== null) {
this.write_(OPEN_PAREN);
this.writeList_(tree.args, COMMA, false);
this.write_(CLOSE_PAREN);
}
},
visitArgumentList: function(tree) {
this.write_(OPEN_PAREN);
this.writeList_(tree.args, COMMA, false);
this.write_(CLOSE_PAREN);
},
visitArrayComprehension: function(tree) {
this.write_(OPEN_SQUARE);
this.visitList(tree.comprehensionList);
this.visitAny(tree.expression);
this.write_(CLOSE_SQUARE);
},
visitArrayLiteralExpression: function(tree) {
this.write_(OPEN_SQUARE);
this.writeList_(tree.elements, COMMA, false);
this.write_(CLOSE_SQUARE);
},
visitArrayPattern: function(tree) {
this.write_(OPEN_SQUARE);
this.writeList_(tree.elements, COMMA, false);
this.write_(CLOSE_SQUARE);
},
visitArrowFunctionExpression: function(tree) {
if (tree.functionKind) {
this.write_(tree.functionKind);
this.writeSpace_();
}
this.write_(OPEN_PAREN);
this.visitAny(tree.parameterList);
this.write_(CLOSE_PAREN);
this.writeSpace_();
this.write_(ARROW);
this.writeSpace_();
this.visitAny(tree.body);
},
visitAssignmentElement: function(tree) {
this.visitAny(tree.assignment);
if (tree.initializer) {
this.writeSpace_();
this.write_(EQUAL);
this.writeSpace_();
this.visitAny(tree.initializer);
}
},
visitAwaitExpression: function(tree) {
this.write_(AWAIT);
this.writeSpace_();
this.visitAny(tree.expression);
},
visitBinaryExpression: function(tree) {
var left = tree.left;
this.visitAny(left);
var operator = tree.operator;
if (left.type === POSTFIX_EXPRESSION && requiresSpaceBetween(left.operator.type, operator.type)) {
this.writeRequiredSpace_();
} else {
this.writeSpace_();
}
this.write_(operator);
var right = tree.right;
if (right.type === UNARY_EXPRESSION && requiresSpaceBetween(operator.type, right.operator.type)) {
this.writeRequiredSpace_();
} else {
this.writeSpace_();
}
this.visitAny(right);
},
visitBindingElement: function(tree) {
var typeAnnotation = this.currentParameterTypeAnnotation_;
this.currentParameterTypeAnnotation_ = null;
this.visitAny(tree.binding);
this.writeTypeAnnotation_(typeAnnotation);
if (tree.initializer) {
this.writeSpace_();
this.write_(EQUAL);
this.writeSpace_();
this.visitAny(tree.initializer);
}
},
visitBindingIdentifier: function(tree) {
this.write_(tree.identifierToken);
},
visitBlock: function(tree) {
this.write_(OPEN_CURLY);
this.writelnList_(tree.statements);
this.write_(CLOSE_CURLY);
},
visitBreakStatement: function(tree) {
this.write_(BREAK);
if (tree.name !== null) {
this.writeSpace_();
this.write_(tree.name);
}
this.write_(SEMI_COLON);
},
visitCallExpression: function(tree) {
this.visitAny(tree.operand);
this.visitAny(tree.args);
},
visitCaseClause: function(tree) {
this.write_(CASE);
this.writeSpace_();
this.visitAny(tree.expression);
this.write_(COLON);
this.indentDepth_++;
this.writelnList_(tree.statements);
this.indentDepth_--;
},
visitCatch: function(tree) {
this.write_(CATCH);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.binding);
this.write_(CLOSE_PAREN);
this.writeSpace_();
this.visitAny(tree.catchBody);
},
visitClassShared_: function(tree) {
this.writeAnnotations_(tree.annotations);
this.write_(CLASS);
this.writeSpace_();
this.visitAny(tree.name);
if (tree.superClass !== null) {
this.writeSpace_();
this.write_(EXTENDS);
this.writeSpace_();
this.visitAny(tree.superClass);
}
this.writeSpace_();
this.write_(OPEN_CURLY);
this.writelnList_(tree.elements);
this.write_(CLOSE_CURLY);
},
visitClassDeclaration: function(tree) {
this.visitClassShared_(tree);
},
visitClassExpression: function(tree) {
this.visitClassShared_(tree);
},
visitCommaExpression: function(tree) {
this.writeList_(tree.expressions, COMMA, false);
},
visitComprehensionFor: function(tree) {
this.write_(FOR);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.left);
this.writeSpace_();
this.write_(OF);
this.writeSpace_();
this.visitAny(tree.iterator);
this.write_(CLOSE_PAREN);
this.writeSpace_();
},
visitComprehensionIf: function(tree) {
this.write_(IF);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.expression);
this.write_(CLOSE_PAREN);
this.writeSpace_();
},
visitComputedPropertyName: function(tree) {
this.write_(OPEN_SQUARE);
this.visitAny(tree.expression);
this.write_(CLOSE_SQUARE);
},
visitConditionalExpression: function(tree) {
this.visitAny(tree.condition);
this.writeSpace_();
this.write_(QUESTION);
this.writeSpace_();
this.visitAny(tree.left);
this.writeSpace_();
this.write_(COLON);
this.writeSpace_();
this.visitAny(tree.right);
},
visitContinueStatement: function(tree) {
this.write_(CONTINUE);
if (tree.name !== null) {
this.writeSpace_();
this.write_(tree.name);
}
this.write_(SEMI_COLON);
},
visitCoverInitializedName: function(tree) {
this.write_(tree.name);
this.writeSpace_();
this.write_(tree.equalToken);
this.writeSpace_();
this.visitAny(tree.initializer);
},
visitDebuggerStatement: function(tree) {
this.write_(DEBUGGER);
this.write_(SEMI_COLON);
},
visitDefaultClause: function(tree) {
this.write_(DEFAULT);
this.write_(COLON);
this.indentDepth_++;
this.writelnList_(tree.statements);
this.indentDepth_--;
},
visitDoWhileStatement: function(tree) {
this.write_(DO);
this.visitAnyBlockOrIndent_(tree.body);
this.writeSpace_();
this.write_(WHILE);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.condition);
this.write_(CLOSE_PAREN);
this.write_(SEMI_COLON);
},
visitEmptyStatement: function(tree) {
this.write_(SEMI_COLON);
},
visitExportDeclaration: function(tree) {
this.writeAnnotations_(tree.annotations);
this.write_(EXPORT);
this.writeSpace_();
this.visitAny(tree.declaration);
},
visitExportDefault: function(tree) {
this.write_(DEFAULT);
this.writeSpace_();
this.visitAny(tree.expression);
switch (tree.expression.type) {
case CLASS_DECLARATION:
case FUNCTION_DECLARATION:
break;
default:
this.write_(SEMI_COLON);
}
},
visitNamedExport: function(tree) {
this.visitAny(tree.specifierSet);
if (tree.moduleSpecifier) {
this.writeSpace_();
this.write_(FROM);
this.writeSpace_();
this.visitAny(tree.moduleSpecifier);
}
this.write_(SEMI_COLON);
},
visitExportSpecifier: function(tree) {
this.write_(tree.lhs);
if (tree.rhs) {
this.writeSpace_();
this.write_(AS);
this.writeSpace_();
this.write_(tree.rhs);
}
},
visitExportSpecifierSet: function(tree) {
this.write_(OPEN_CURLY);
this.writeList_(tree.specifiers, COMMA, false);
this.write_(CLOSE_CURLY);
},
visitExportStar: function(tree) {
this.write_(STAR);
},
visitExpressionStatement: function(tree) {
this.visitAny(tree.expression);
this.write_(SEMI_COLON);
},
visitFinally: function(tree) {
this.write_(FINALLY);
this.writeSpace_();
this.visitAny(tree.block);
},
visitForOfStatement: function(tree) {
this.write_(FOR);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.initializer);
this.writeSpace_();
this.write_(OF);
this.writeSpace_();
this.visitAny(tree.collection);
this.write_(CLOSE_PAREN);
this.visitAnyBlockOrIndent_(tree.body);
},
visitForInStatement: function(tree) {
this.write_(FOR);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.initializer);
this.writeSpace_();
this.write_(IN);
this.writeSpace_();
this.visitAny(tree.collection);
this.write_(CLOSE_PAREN);
this.visitAnyBlockOrIndent_(tree.body);
},
visitForStatement: function(tree) {
this.write_(FOR);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.initializer);
this.write_(SEMI_COLON);
this.writeSpace_();
this.visitAny(tree.condition);
this.write_(SEMI_COLON);
this.writeSpace_();
this.visitAny(tree.increment);
this.write_(CLOSE_PAREN);
this.visitAnyBlockOrIndent_(tree.body);
},
visitFormalParameterList: function(tree) {
var first = true;
for (var i = 0; i < tree.parameters.length; i++) {
var parameter = tree.parameters[i];
if (first) {
first = false;
} else {
this.write_(COMMA);
this.writeSpace_();
}
this.visitAny(parameter);
}
},
visitFormalParameter: function(tree) {
this.writeAnnotations_(tree.annotations, false);
this.currentParameterTypeAnnotation_ = tree.typeAnnotation;
this.visitAny(tree.parameter);
this.currentParameterTypeAnnotation_ = null;
},
visitFunctionBody: function(tree) {
this.write_(OPEN_CURLY);
this.writelnList_(tree.statements);
this.write_(CLOSE_CURLY);
},
visitFunctionDeclaration: function(tree) {
this.visitFunction_(tree);
},
visitFunctionExpression: function(tree) {
this.visitFunction_(tree);
},
visitFunction_: function(tree) {
this.writeAnnotations_(tree.annotations);
if (tree.isAsyncFunction())
this.write_(tree.functionKind);
this.write_(FUNCTION);
if (tree.isGenerator())
this.write_(tree.functionKind);
if (tree.name) {
this.writeSpace_();
this.visitAny(tree.name);
}
this.write_(OPEN_PAREN);
this.visitAny(tree.parameterList);
this.write_(CLOSE_PAREN);
this.writeTypeAnnotation_(tree.typeAnnotation);
this.writeSpace_();
this.visitAny(tree.body);
},
visitGeneratorComprehension: function(tree) {
this.write_(OPEN_PAREN);
this.visitList(tree.comprehensionList);
this.visitAny(tree.expression);
this.write_(CLOSE_PAREN);
},
visitGetAccessor: function(tree) {
this.writeAnnotations_(tree.annotations);
if (tree.isStatic) {
this.write_(STATIC);
this.writeSpace_();
}
this.write_(GET);
this.writeSpace_();
this.visitAny(tree.name);
this.write_(OPEN_PAREN);
this.write_(CLOSE_PAREN);
this.writeSpace_();
this.writeTypeAnnotation_(tree.typeAnnotation);
this.visitAny(tree.body);
},
visitIdentifierExpression: function(tree) {
this.write_(tree.identifierToken);
},
visitIfStatement: function(tree) {
this.write_(IF);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.condition);
this.write_(CLOSE_PAREN);
this.visitAnyBlockOrIndent_(tree.ifClause);
if (tree.elseClause) {
if (tree.ifClause.type === BLOCK)
this.writeSpace_();
this.write_(ELSE);
if (tree.elseClause.type === IF_STATEMENT) {
this.writeSpace_();
this.visitAny(tree.elseClause);
} else {
this.visitAnyBlockOrIndent_(tree.elseClause);
}
}
},
visitAnyBlockOrIndent_: function(tree) {
if (tree.type === BLOCK) {
this.writeSpace_();
this.visitAny(tree);
} else {
this.visitAnyIndented_(tree);
}
},
visitAnyIndented_: function(tree) {
var indent = arguments[1] !== (void 0) ? arguments[1] : 1;
if (this.prettyPrint_) {
this.indentDepth_ += indent;
this.writeln_();
}
this.visitAny(tree);
if (this.prettyPrint_) {
this.indentDepth_ -= indent;
this.writeln_();
}
},
visitImportDeclaration: function(tree) {
this.write_(IMPORT);
this.writeSpace_();
if (tree.importClause) {
this.visitAny(tree.importClause);
this.writeSpace_();
this.write_(FROM);
this.writeSpace_();
}
this.visitAny(tree.moduleSpecifier);
this.write_(SEMI_COLON);
},
visitImportSpecifier: function(tree) {
this.write_(tree.lhs);
if (tree.rhs !== null) {
this.writeSpace_();
this.write_(AS);
this.writeSpace_();
this.write_(tree.rhs);
}
},
visitImportSpecifierSet: function(tree) {
if (tree.specifiers.type == STAR) {
this.write_(STAR);
} else {
this.write_(OPEN_CURLY);
this.writelnList_(tree.specifiers, COMMA);
this.write_(CLOSE_CURLY);
}
},
visitLabelledStatement: function(tree) {
this.write_(tree.name);
this.write_(COLON);
this.writeSpace_();
this.visitAny(tree.statement);
},
visitLiteralExpression: function(tree) {
this.write_(tree.literalToken);
},
visitLiteralPropertyName: function(tree) {
this.write_(tree.literalToken);
},
visitMemberExpression: function(tree) {
this.visitAny(tree.operand);
if (tree.operand.type === LITERAL_EXPRESSION && tree.operand.literalToken.type === NUMBER) {
if (!/\.|e|E/.test(tree.operand.literalToken.value))
this.writeRequiredSpace_();
}
this.write_(PERIOD);
this.write_(tree.memberName);
},
visitMemberLookupExpression: function(tree) {
this.visitAny(tree.operand);
this.write_(OPEN_SQUARE);
this.visitAny(tree.memberExpression);
this.write_(CLOSE_SQUARE);
},
visitSyntaxErrorTree: function(tree) {
this.write_('(function() {' + ("throw SyntaxError(" + JSON.stringify(tree.message) + ");") + '})()');
},
visitModule: function(tree) {
this.writelnList_(tree.scriptItemList, null);
},
visitModuleSpecifier: function(tree) {
this.write_(tree.token);
},
visitModuleDeclaration: function(tree) {
this.write_(MODULE);
this.writeSpace_();
this.write_(tree.identifier);
this.writeSpace_();
this.write_(FROM);
this.writeSpace_();
this.visitAny(tree.expression);
this.write_(SEMI_COLON);
},
visitNewExpression: function(tree) {
this.write_(NEW);
this.writeSpace_();
this.visitAny(tree.operand);
this.visitAny(tree.args);
},
visitObjectLiteralExpression: function(tree) {
this.write_(OPEN_CURLY);
if (tree.propertyNameAndValues.length > 1)
this.writeln_();
this.writelnList_(tree.propertyNameAndValues, COMMA);
if (tree.propertyNameAndValues.length > 1)
this.writeln_();
this.write_(CLOSE_CURLY);
},
visitObjectPattern: function(tree) {
this.write_(OPEN_CURLY);
this.writelnList_(tree.fields, COMMA);
this.write_(CLOSE_CURLY);
},
visitObjectPatternField: function(tree) {
this.visitAny(tree.name);
if (tree.element !== null) {
this.write_(COLON);
this.writeSpace_();
this.visitAny(tree.element);
}
},
visitParenExpression: function(tree) {
this.write_(OPEN_PAREN);
$traceurRuntime.superCall(this, $ParseTreeWriter.prototype, "visitParenExpression", [tree]);
this.write_(CLOSE_PAREN);
},
visitPostfixExpression: function(tree) {
this.visitAny(tree.operand);
if (tree.operand.type === POSTFIX_EXPRESSION && tree.operand.operator.type === tree.operator.type) {
this.writeRequiredSpace_();
}
this.write_(tree.operator);
},
visitPredefinedType: function(tree) {
this.write_(tree.typeToken);
},
visitScript: function(tree) {
this.writelnList_(tree.scriptItemList, null);
},
visitPropertyMethodAssignment: function(tree) {
this.writeAnnotations_(tree.annotations);
if (tree.isStatic) {
this.write_(STATIC);
this.writeSpace_();
}
if (tree.isGenerator())
this.write_(STAR);
if (tree.isAsyncFunction())
this.write_(ASYNC);
this.visitAny(tree.name);
this.write_(OPEN_PAREN);
this.visitAny(tree.parameterList);
this.write_(CLOSE_PAREN);
this.writeSpace_();
this.writeTypeAnnotation_(tree.typeAnnotation);
this.visitAny(tree.body);
},
visitPropertyNameAssignment: function(tree) {
this.visitAny(tree.name);
this.write_(COLON);
this.writeSpace_();
this.visitAny(tree.value);
},
visitPropertyNameShorthand: function(tree) {
this.write_(tree.name);
},
visitTemplateLiteralExpression: function(tree) {
if (tree.operand) {
this.visitAny(tree.operand);
this.writeSpace_();
}
this.writeRaw_(BACK_QUOTE);
this.visitList(tree.elements);
this.writeRaw_(BACK_QUOTE);
},
visitTemplateLiteralPortion: function(tree) {
this.writeRaw_(tree.value);
},
visitTemplateSubstitution: function(tree) {
this.writeRaw_('$');
this.writeRaw_(OPEN_CURLY);
this.visitAny(tree.expression);
this.writeRaw_(CLOSE_CURLY);
},
visitReturnStatement: function(tree) {
this.write_(RETURN);
this.writeSpace_(tree.expression);
this.visitAny(tree.expression);
this.write_(SEMI_COLON);
},
visitRestParameter: function(tree) {
this.write_(DOT_DOT_DOT);
this.write_(tree.identifier.identifierToken);
this.writeTypeAnnotation_(this.currentParameterTypeAnnotation_);
},
visitSetAccessor: function(tree) {
this.writeAnnotations_(tree.annotations);
if (tree.isStatic) {
this.write_(STATIC);
this.writeSpace_();
}
this.write_(SET);
this.writeSpace_();
this.visitAny(tree.name);
this.write_(OPEN_PAREN);
this.visitAny(tree.parameterList);
this.write_(CLOSE_PAREN);
this.writeSpace_();
this.visitAny(tree.body);
},
visitSpreadExpression: function(tree) {
this.write_(DOT_DOT_DOT);
this.visitAny(tree.expression);
},
visitSpreadPatternElement: function(tree) {
this.write_(DOT_DOT_DOT);
this.visitAny(tree.lvalue);
},
visitStateMachine: function(tree) {
throw new Error('State machines cannot be converted to source');
},
visitSuperExpression: function(tree) {
this.write_(SUPER);
},
visitSwitchStatement: function(tree) {
this.write_(SWITCH);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.expression);
this.write_(CLOSE_PAREN);
this.writeSpace_();
this.write_(OPEN_CURLY);
this.writelnList_(tree.caseClauses);
this.write_(CLOSE_CURLY);
},
visitThisExpression: function(tree) {
this.write_(THIS);
},
visitThrowStatement: function(tree) {
this.write_(THROW);
this.writeSpace_();
this.visitAny(tree.value);
this.write_(SEMI_COLON);
},
visitTryStatement: function(tree) {
this.write_(TRY);
this.writeSpace_();
this.visitAny(tree.body);
if (tree.catchBlock) {
this.writeSpace_();
this.visitAny(tree.catchBlock);
}
if (tree.finallyBlock) {
this.writeSpace_();
this.visitAny(tree.finallyBlock);
}
},
visitTypeName: function(tree) {
if (tree.moduleName) {
this.visitAny(tree.moduleName);
this.write_(PERIOD);
}
this.write_(tree.name);
},
visitUnaryExpression: function(tree) {
var op = tree.operator;
this.write_(op);
var operand = tree.operand;
if (operand.type === UNARY_EXPRESSION && requiresSpaceBetween(op.type, operand.operator.type)) {
this.writeRequiredSpace_();
}
this.visitAny(operand);
},
visitVariableDeclarationList: function(tree) {
this.write_(tree.declarationType);
this.writeSpace_();
this.writeList_(tree.declarations, COMMA, true, 2);
},
visitVariableDeclaration: function(tree) {
this.visitAny(tree.lvalue);
this.writeTypeAnnotation_(tree.typeAnnotation);
if (tree.initializer !== null) {
this.writeSpace_();
this.write_(EQUAL);
this.writeSpace_();
this.visitAny(tree.initializer);
}
},
visitVariableStatement: function(tree) {
$traceurRuntime.superCall(this, $ParseTreeWriter.prototype, "visitVariableStatement", [tree]);
this.write_(SEMI_COLON);
},
visitWhileStatement: function(tree) {
this.write_(WHILE);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.condition);
this.write_(CLOSE_PAREN);
this.visitAnyBlockOrIndent_(tree.body);
},
visitWithStatement: function(tree) {
this.write_(WITH);
this.writeSpace_();
this.write_(OPEN_PAREN);
this.visitAny(tree.expression);
this.write_(CLOSE_PAREN);
this.writeSpace_();
this.visitAny(tree.body);
},
visitYieldExpression: function(tree) {
this.write_(YIELD);
if (tree.isYieldFor)
this.write_(STAR);
if (tree.expression) {
this.writeSpace_();
this.visitAny(tree.expression);
}
},
writeCurrentln_: function() {
this.result_ += this.currentLine_ + NEW_LINE;
},
writeln_: function() {
if (this.currentLineComment_) {
while (this.currentLine_.length < LINE_LENGTH) {
this.currentLine_ += ' ';
}
this.currentLine_ += ' // ' + this.currentLineComment_;
this.currentLineComment_ = null;
}
if (this.currentLine_)
this.writeCurrentln_();
this.currentLine_ = '';
},
writelnList_: function(list, delimiter) {
if (delimiter) {
this.writeList_(list, delimiter, true);
} else {
if (list.length > 0)
this.writeln_();
this.writeList_(list, null, true);
if (list.length > 0)
this.writeln_();
}
},
writeList_: function(list, delimiter, writeNewLine) {
var indent = arguments[3] !== (void 0) ? arguments[3] : 0;
var first = true;
for (var i = 0; i < list.length; i++) {
var element = list[i];
if (first) {
first = false;
} else {
if (delimiter !== null) {
this.write_(delimiter);
if (!writeNewLine)
this.writeSpace_();
}
if (writeNewLine) {
if (i === 1)
this.indentDepth_ += indent;
this.writeln_();
}
}
this.visitAny(element);
}
if (writeNewLine && list.length > 1)
this.indentDepth_ -= indent;
},
writeRaw_: function(value) {
this.currentLine_ += value;
},
write_: function(value) {
if (value === CLOSE_CURLY)
this.indentDepth_--;
if (value !== null) {
if (this.prettyPrint_) {
if (!this.currentLine_) {
for (var i = 0,
indent = this.indentDepth_; i < indent; i++) {
this.currentLine_ += ' ';
}
}
}
if (this.needsSpace_(value))
this.currentLine_ += ' ';
this.currentLine_ += value;
}
if (value === OPEN_CURLY)
this.indentDepth_++;
},
writeSpace_: function() {
var useSpace = arguments[0] !== (void 0) ? arguments[0] : this.prettyPrint_;
if (useSpace && !endsWithSpace(this.currentLine_))
this.currentLine_ += ' ';
},
writeRequiredSpace_: function() {
this.writeSpace_(true);
},
writeTypeAnnotation_: function(typeAnnotation) {
if (typeAnnotation !== null) {
this.write_(COLON);
this.writeSpace_();
this.visitAny(typeAnnotation);
}
},
writeAnnotations_: function(annotations) {
var writeNewLine = arguments[1] !== (void 0) ? arguments[1] : this.prettyPrint_;
if (annotations.length > 0) {
this.writeList_(annotations, null, writeNewLine);
if (writeNewLine)
this.writeln_();
}
},
needsSpace_: function(token) {
var line = this.currentLine_;
if (!line)
return false;
var lastCode = line.charCodeAt(line.length - 1);
if (isWhitespace(lastCode))
return false;
var firstCode = token.toString().charCodeAt(0);
return isIdentifierPart(firstCode) && (isIdentifierPart(lastCode) || lastCode === 47);
}
}, {}, ParseTreeVisitor);
function requiresSpaceBetween(first, second) {
return (first === MINUS || first === MINUS_MINUS) && (second === MINUS || second === MINUS_MINUS) || (first === PLUS || first === PLUS_PLUS) && (second === PLUS || second === PLUS_PLUS);
}
function endsWithSpace(s) {
return isWhitespace(s.charCodeAt(s.length - 1));
}
return {get ParseTreeWriter() {
return ParseTreeWriter;
}};
});
System.register("traceur@0.0.52/src/outputgeneration/ParseTreeMapWriter", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/outputgeneration/ParseTreeMapWriter";
var ParseTreeWriter = System.get("traceur@0.0.52/src/outputgeneration/ParseTreeWriter").ParseTreeWriter;
var ParseTreeMapWriter = function ParseTreeMapWriter(sourceMapGenerator) {
var options = arguments[1];
$traceurRuntime.superCall(this, $ParseTreeMapWriter.prototype, "constructor", [options]);
this.sourceMapGenerator_ = sourceMapGenerator;
this.outputLineCount_ = 1;
this.isFirstMapping_ = true;
};
var $ParseTreeMapWriter = ParseTreeMapWriter;
($traceurRuntime.createClass)(ParseTreeMapWriter, {
visitAny: function(tree) {
if (!tree) {
return;
}
if (tree.location)
this.enterBranch(tree.location);
$traceurRuntime.superCall(this, $ParseTreeMapWriter.prototype, "visitAny", [tree]);
if (tree.location)
this.exitBranch(tree.location);
},
writeCurrentln_: function() {
$traceurRuntime.superCall(this, $ParseTreeMapWriter.prototype, "writeCurrentln_", []);
this.flushMappings();
this.outputLineCount_++;
this.generated_ = {
line: this.outputLineCount_,
column: 0
};
this.flushMappings();
},
write_: function(value) {
if (this.entered_) {
this.generate();
$traceurRuntime.superCall(this, $ParseTreeMapWriter.prototype, "write_", [value]);
this.generate();
} else {
this.generate();
$traceurRuntime.superCall(this, $ParseTreeMapWriter.prototype, "write_", [value]);
this.generate();
}
},
generate: function() {
var column = this.currentLine_.length ? this.currentLine_.length - 1 : 0;
this.generated_ = {
line: this.outputLineCount_,
column: column
};
this.flushMappings();
},
enterBranch: function(location) {
this.originate(location.start);
this.entered_ = true;
},
exitBranch: function(location) {
var position = location.end;
var endOfPreviousToken = {
line: position.line,
column: position.column ? position.column - 1 : 0,
source: {
name: position.source.name,
contents: position.source.contents
}
};
this.originate(endOfPreviousToken);
this.entered_ = false;
},
originate: function(position) {
var line = position.line + 1;
if (this.original_ && this.original_.line !== line)
this.flushMappings();
this.original_ = {
line: line,
column: position.column || 0
};
if (position.source.name !== this.sourceName_) {
this.sourceName_ = position.source.name;
this.sourceMapGenerator_.setSourceContent(position.source.name, position.source.contents);
}
this.flushMappings();
},
flushMappings: function() {
if (this.original_ && this.generated_) {
this.addMapping();
this.original_ = null;
this.generated_ = null;
}
},
isSame: function(lhs, rhs) {
return lhs.line === rhs.line && lhs.column === rhs.column;
},
isSameMapping: function() {
if (!this.previousMapping_)
return false;
if (this.isSame(this.previousMapping_.generated, this.generated_) && this.isSame(this.previousMapping_.original, this.original_))
return true;
;
},
addMapping: function() {
if (this.isSameMapping())
return;
var mapping = {
generated: this.generated_,
original: this.original_,
source: this.sourceName_
};
this.sourceMapGenerator_.addMapping(mapping);
this.previousMapping_ = mapping;
}
}, {}, ParseTreeWriter);
return {get ParseTreeMapWriter() {
return ParseTreeMapWriter;
}};
});
System.register("traceur@0.0.52/src/outputgeneration/SourceMapIntegration", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/outputgeneration/SourceMapIntegration";
function makeDefine(mapping, id) {
var require = function(id) {
return mapping[id];
};
var exports = mapping[id] = {};
var module = null;
return function(factory) {
factory(require, exports, module);
};
}
var define,
m = {};
define = makeDefine(m, './util');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port;
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = (path.charAt(0) === '/');
var parts = path.split(/\/+/);
for (var part,
up = 0,
i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
function join(aRoot, aPath) {
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
}
;
exports.compareByOriginalPositions = compareByOriginalPositions;
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
;
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
define = makeDefine(m, './array-set');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
var util = require('./util');
function ArraySet() {
this._array = [];
this._set = {};
}
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0,
len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr));
};
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
define = makeDefine(m, './base64');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('').forEach(function(ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
define = makeDefine(m, './base64-vlq');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
var base64 = require('./base64');
var VLQ_BASE_SHIFT = 5;
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
var VLQ_BASE_MASK = VLQ_BASE - 1;
var VLQ_CONTINUATION_BIT = VLQ_BASE;
function toVLQSigned(aValue) {
return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0;
}
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative ? -shifted : shifted;
}
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation,
digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
define = makeDefine(m, './binary-search');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
return aHaystack[mid];
} else if (cmp > 0) {
if (aHigh - mid > 1) {
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
return aHaystack[mid];
} else {
if (mid - aLow > 1) {
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
return aLow < 0 ? null : aHaystack[aLow];
}
}
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) : null;
};
});
define = makeDefine(m, './source-map-generator');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function(mapping) {
var newMapping = {generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}};
if (mapping.source) {
newMapping.source = mapping.source;
if (sourceRoot) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function(sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent !== null) {
if (!this._sourcesContents) {
this._sourcesContents = {};
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else {
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
if (!aSourceFile) {
if (!aSourceMapConsumer.file) {
throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.');
}
aSourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
if (sourceRoot) {
aSourceFile = util.relative(sourceRoot, aSourceFile);
}
var newSources = new ArraySet();
var newNames = new ArraySet();
this._mappings.forEach(function(mapping) {
if (mapping.source === aSourceFile && mapping.originalLine) {
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source !== null) {
mapping.source = original.source;
if (aSourceMapPath) {
mapping.source = util.join(aSourceMapPath, mapping.source);
}
if (sourceRoot) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name !== null && mapping.name !== null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
aSourceMapConsumer.sources.forEach(function(sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
if (aSourceMapPath) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
return;
} else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
return;
} else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0,
len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
} else {
if (i > 0) {
if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
continue;
}
result += ',';
}
}
result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource);
previousSource = this._sources.indexOf(mapping.source);
result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function(source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
}, this);
};
SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
return JSON.stringify(this);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
define = makeDefine(m, './source-map-consumer');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
var util = require('./util');
var binarySearch = require('./binary-search');
var ArraySet = require('./array-set').ArraySet;
var base64VLQ = require('./base64-vlq');
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
SourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(SourceMapConsumer.prototype);
smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
smc.file = aSourceMap._file;
smc.__generatedMappings = aSourceMap._mappings.slice().sort(util.compareByGeneratedPositions);
smc.__originalMappings = aSourceMap._mappings.slice().sort(util.compareByOriginalPositions);
return smc;
};
SourceMapConsumer.prototype._version = 3;
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {get: function() {
return this._sources.toArray().map(function(s) {
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
}, this);
}});
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {get: function() {
if (!this.__generatedMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {get: function() {
if (!this.__originalMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}});
SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
} else if (str.charAt(0) === ',') {
str = str.slice(1);
} else {
mapping = {};
mapping.generatedLine = generatedLine;
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
temp = base64VLQ.decode(str);
mapping.source = this._sources.at(previousSource + temp.value);
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this.__generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
this.__originalMappings.push(mapping);
}
}
}
this.__generatedMappings.sort(util.compareByGeneratedPositions);
this.__originalMappings.sort(util.compareByOriginalPositions);
};
SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) {
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator);
};
SourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var mapping = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions);
if (mapping && mapping.generatedLine === needle.generatedLine) {
var source = util.getArg(mapping, 'source', null);
if (source && this.sourceRoot) {
source = util.join(this.sourceRoot, source);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
SourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot && (url = util.urlParse(this.sourceRoot))) {
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
}
if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
};
SourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
if (this.sourceRoot) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
var mapping = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
};
}
return {
line: null,
column: null
};
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function(mapping) {
var source = mapping.source;
if (source && sourceRoot) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name
};
}).forEach(aCallback, context);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
define = makeDefine(m, './source-node');
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function(require, exports, module) {
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
var REGEX_NEWLINE = /(\r?\n)/g;
var REGEX_CHARACTER = /\r\n|[\s\S]/g;
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine === undefined ? null : aLine;
this.column = aColumn === undefined ? null : aColumn;
this.source = aSource === undefined ? null : aSource;
this.name = aName === undefined ? null : aName;
if (aChunks != null)
this.add(aChunks);
}
SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
var node = new SourceNode();
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var shiftNextLine = function() {
var lineContents = remainingLines.shift();
var newLine = remainingLines.shift() || "";
return lineContents + newLine;
};
var lastGeneratedLine = 1,
lastGeneratedColumn = 0;
var lastMapping = null;
aSourceMapConsumer.eachMapping(function(mapping) {
if (lastMapping !== null) {
if (lastGeneratedLine < mapping.generatedLine) {
var code = "";
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
} else {
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
lastMapping = mapping;
return;
}
}
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
if (remainingLines.length > 0) {
if (lastMapping) {
addMappingWithCode(lastMapping, shiftNextLine());
}
node.add(remainingLines.join(""));
}
aSourceMapConsumer.sources.forEach(function(sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name));
}
}
};
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function(chunk) {
this.add(chunk);
}, this);
} else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length - 1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
} else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.unshift(aChunk);
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0,
len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
} else {
if (chunk !== '') {
aFn(chunk, {
source: this.source,
line: this.line,
column: this.column,
name: this.name
});
}
}
}
};
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len - 1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
} else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
} else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
for (var i = 0,
len = this.children.length; i < len; i++) {
if (this.children[i] instanceof SourceNode) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0,
len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function(chunk) {
str += chunk;
});
return str;
};
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function(chunk, original) {
generated.code += chunk;
if (original.source !== null && original.line !== null && original.column !== null) {
if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({generated: {
line: generated.line,
column: generated.column
}});
lastOriginalSource = null;
sourceMappingActive = false;
}
chunk.match(REGEX_CHARACTER).forEach(function(ch, idx, array) {
if (REGEX_NEWLINE.test(ch)) {
generated.line++;
generated.column = 0;
if (idx + 1 === array.length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column += ch.length;
}
});
});
this.walkSourceContents(function(sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return {
code: generated.code,
map: map
};
};
exports.SourceNode = SourceNode;
});
var SourceMapGenerator = m['./source-map-generator'].SourceMapGenerator;
var SourceMapConsumer = m['./source-map-consumer'].SourceMapConsumer;
var SourceNode = m['./source-node'].SourceNode;
return {
get SourceMapGenerator() {
return SourceMapGenerator;
},
get SourceMapConsumer() {
return SourceMapConsumer;
},
get SourceNode() {
return SourceNode;
}
};
});
System.register("traceur@0.0.52/src/outputgeneration/toSource", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/outputgeneration/toSource";
var ParseTreeMapWriter = System.get("traceur@0.0.52/src/outputgeneration/ParseTreeMapWriter").ParseTreeMapWriter;
var ParseTreeWriter = System.get("traceur@0.0.52/src/outputgeneration/ParseTreeWriter").ParseTreeWriter;
var SourceMapGenerator = System.get("traceur@0.0.52/src/outputgeneration/SourceMapIntegration").SourceMapGenerator;
function toSource(tree) {
var options = arguments[1];
var sourceMapGenerator = options && options.sourceMapGenerator;
if (!sourceMapGenerator && options && options.sourceMaps) {
sourceMapGenerator = new SourceMapGenerator({
file: options.filename,
sourceRoot: null
});
}
var writer;
if (sourceMapGenerator)
writer = new ParseTreeMapWriter(sourceMapGenerator, options);
else
writer = new ParseTreeWriter(options);
writer.visitAny(tree);
return [writer.toString(), sourceMapGenerator && sourceMapGenerator.toString()];
}
return {get toSource() {
return toSource;
}};
});
System.register("traceur@0.0.52/src/outputgeneration/TreeWriter", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/outputgeneration/TreeWriter";
var toSource = System.get("traceur@0.0.52/src/outputgeneration/toSource").toSource;
function write(tree) {
var options = arguments[1];
var $__613 = $traceurRuntime.assertObject(toSource(tree, options)),
result = $__613[0],
sourceMap = $__613[1];
if (sourceMap)
options.generatedSourceMap = sourceMap;
return result;
}
var TreeWriter = function TreeWriter() {};
($traceurRuntime.createClass)(TreeWriter, {}, {});
TreeWriter.write = write;
return {
get write() {
return write;
},
get TreeWriter() {
return TreeWriter;
}
};
});
System.register("traceur@0.0.52/src/syntax/ParseTreeValidator", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/syntax/ParseTreeValidator";
var NewExpression = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").NewExpression;
var ParseTreeVisitor = System.get("traceur@0.0.52/src/syntax/ParseTreeVisitor").ParseTreeVisitor;
var TreeWriter = System.get("traceur@0.0.52/src/outputgeneration/TreeWriter").TreeWriter;
var $__617 = System.get("traceur@0.0.52/src/syntax/TokenType"),
AMPERSAND = $__617.AMPERSAND,
AMPERSAND_EQUAL = $__617.AMPERSAND_EQUAL,
AND = $__617.AND,
BAR = $__617.BAR,
BAR_EQUAL = $__617.BAR_EQUAL,
CARET = $__617.CARET,
CARET_EQUAL = $__617.CARET_EQUAL,
CLOSE_ANGLE = $__617.CLOSE_ANGLE,
EQUAL = $__617.EQUAL,
EQUAL_EQUAL = $__617.EQUAL_EQUAL,
EQUAL_EQUAL_EQUAL = $__617.EQUAL_EQUAL_EQUAL,
GREATER_EQUAL = $__617.GREATER_EQUAL,
IDENTIFIER = $__617.IDENTIFIER,
IN = $__617.IN,
INSTANCEOF = $__617.INSTANCEOF,
LEFT_SHIFT = $__617.LEFT_SHIFT,
LEFT_SHIFT_EQUAL = $__617.LEFT_SHIFT_EQUAL,
LESS_EQUAL = $__617.LESS_EQUAL,
MINUS = $__617.MINUS,
MINUS_EQUAL = $__617.MINUS_EQUAL,
NOT_EQUAL = $__617.NOT_EQUAL,
NOT_EQUAL_EQUAL = $__617.NOT_EQUAL_EQUAL,
NUMBER = $__617.NUMBER,
OPEN_ANGLE = $__617.OPEN_ANGLE,
OR = $__617.OR,
PERCENT = $__617.PERCENT,
PERCENT_EQUAL = $__617.PERCENT_EQUAL,
PLUS = $__617.PLUS,
PLUS_EQUAL = $__617.PLUS_EQUAL,
RIGHT_SHIFT = $__617.RIGHT_SHIFT,
RIGHT_SHIFT_EQUAL = $__617.RIGHT_SHIFT_EQUAL,
SLASH = $__617.SLASH,
SLASH_EQUAL = $__617.SLASH_EQUAL,
STAR = $__617.STAR,
STAR_EQUAL = $__617.STAR_EQUAL,
STRING = $__617.STRING,
UNSIGNED_RIGHT_SHIFT = $__617.UNSIGNED_RIGHT_SHIFT,
UNSIGNED_RIGHT_SHIFT_EQUAL = $__617.UNSIGNED_RIGHT_SHIFT_EQUAL;
var $__618 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
ARRAY_PATTERN = $__618.ARRAY_PATTERN,
ASSIGNMENT_ELEMENT = $__618.ASSIGNMENT_ELEMENT,
BINDING_ELEMENT = $__618.BINDING_ELEMENT,
BINDING_IDENTIFIER = $__618.BINDING_IDENTIFIER,
BLOCK = $__618.BLOCK,
CASE_CLAUSE = $__618.CASE_CLAUSE,
CATCH = $__618.CATCH,
CLASS_DECLARATION = $__618.CLASS_DECLARATION,
COMPUTED_PROPERTY_NAME = $__618.COMPUTED_PROPERTY_NAME,
DEFAULT_CLAUSE = $__618.DEFAULT_CLAUSE,
EXPORT_DEFAULT = $__618.EXPORT_DEFAULT,
EXPORT_SPECIFIER = $__618.EXPORT_SPECIFIER,
EXPORT_SPECIFIER_SET = $__618.EXPORT_SPECIFIER_SET,
EXPORT_STAR = $__618.EXPORT_STAR,
FINALLY = $__618.FINALLY,
FORMAL_PARAMETER = $__618.FORMAL_PARAMETER,
FORMAL_PARAMETER_LIST = $__618.FORMAL_PARAMETER_LIST,
FUNCTION_BODY = $__618.FUNCTION_BODY,
FUNCTION_DECLARATION = $__618.FUNCTION_DECLARATION,
GET_ACCESSOR = $__618.GET_ACCESSOR,
IDENTIFIER_EXPRESSION = $__618.IDENTIFIER_EXPRESSION,
LITERAL_PROPERTY_NAME = $__618.LITERAL_PROPERTY_NAME,
MODULE_DECLARATION = $__618.MODULE_DECLARATION,
MODULE_SPECIFIER = $__618.MODULE_SPECIFIER,
NAMED_EXPORT = $__618.NAMED_EXPORT,
OBJECT_PATTERN = $__618.OBJECT_PATTERN,
OBJECT_PATTERN_FIELD = $__618.OBJECT_PATTERN_FIELD,
PROPERTY_METHOD_ASSIGNMENT = $__618.PROPERTY_METHOD_ASSIGNMENT,
PROPERTY_NAME_ASSIGNMENT = $__618.PROPERTY_NAME_ASSIGNMENT,
PROPERTY_NAME_SHORTHAND = $__618.PROPERTY_NAME_SHORTHAND,
REST_PARAMETER = $__618.REST_PARAMETER,
SET_ACCESSOR = $__618.SET_ACCESSOR,
TEMPLATE_LITERAL_PORTION = $__618.TEMPLATE_LITERAL_PORTION,
TEMPLATE_SUBSTITUTION = $__618.TEMPLATE_SUBSTITUTION,
VARIABLE_DECLARATION_LIST = $__618.VARIABLE_DECLARATION_LIST,
VARIABLE_STATEMENT = $__618.VARIABLE_STATEMENT;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var ValidationError = function ValidationError(tree, message) {
this.tree = tree;
this.message = message;
};
($traceurRuntime.createClass)(ValidationError, {}, {}, Error);
var ParseTreeValidator = function ParseTreeValidator() {
$traceurRuntime.defaultSuperCall(this, $ParseTreeValidator.prototype, arguments);
};
var $ParseTreeValidator = ParseTreeValidator;
($traceurRuntime.createClass)(ParseTreeValidator, {
fail_: function(tree, message) {
throw new ValidationError(tree, message);
},
check_: function(condition, tree, message) {
if (!condition) {
this.fail_(tree, message);
}
},
checkVisit_: function(condition, tree, message) {
this.check_(condition, tree, message);
this.visitAny(tree);
},
checkType_: function(type, tree, message) {
this.checkVisit_(tree.type === type, tree, message);
},
visitArgumentList: function(tree) {
for (var i = 0; i < tree.args.length; i++) {
var argument = tree.args[i];
this.checkVisit_(argument.isAssignmentOrSpread(), argument, 'assignment or spread expected');
}
},
visitArrayLiteralExpression: function(tree) {
for (var i = 0; i < tree.elements.length; i++) {
var element = tree.elements[i];
this.checkVisit_(element === null || element.isAssignmentOrSpread(), element, 'assignment or spread expected');
}
},
visitArrayPattern: function(tree) {
for (var i = 0; i < tree.elements.length; i++) {
var element = tree.elements[i];
this.checkVisit_(element === null || element.type === BINDING_ELEMENT || element.type == ASSIGNMENT_ELEMENT || element.isLeftHandSideExpression() || element.isPattern() || element.isSpreadPatternElement(), element, 'null, sub pattern, left hand side expression or spread expected');
if (element && element.isSpreadPatternElement()) {
this.check_(i === (tree.elements.length - 1), element, 'spread in array patterns must be the last element');
}
}
},
visitBinaryExpression: function(tree) {
switch (tree.operator.type) {
case EQUAL:
case STAR_EQUAL:
case SLASH_EQUAL:
case PERCENT_EQUAL:
case PLUS_EQUAL:
case MINUS_EQUAL:
case LEFT_SHIFT_EQUAL:
case RIGHT_SHIFT_EQUAL:
case UNSIGNED_RIGHT_SHIFT_EQUAL:
case AMPERSAND_EQUAL:
case CARET_EQUAL:
case BAR_EQUAL:
this.check_(tree.left.isLeftHandSideExpression() || tree.left.isPattern(), tree.left, 'left hand side expression or pattern expected');
this.check_(tree.right.isAssignmentExpression(), tree.right, 'assignment expression expected');
break;
case AND:
case OR:
case BAR:
case CARET:
case AMPERSAND:
case EQUAL_EQUAL:
case NOT_EQUAL:
case EQUAL_EQUAL_EQUAL:
case NOT_EQUAL_EQUAL:
case OPEN_ANGLE:
case CLOSE_ANGLE:
case GREATER_EQUAL:
case LESS_EQUAL:
case INSTANCEOF:
case IN:
case LEFT_SHIFT:
case RIGHT_SHIFT:
case UNSIGNED_RIGHT_SHIFT:
case PLUS:
case MINUS:
case STAR:
case SLASH:
case PERCENT:
this.check_(tree.left.isAssignmentExpression(), tree.left, 'assignment expression expected');
this.check_(tree.right.isAssignmentExpression(), tree.right, 'assignment expression expected');
break;
default:
this.fail_(tree, 'unexpected binary operator');
}
this.visitAny(tree.left);
this.visitAny(tree.right);
},
visitBindingElement: function(tree) {
var binding = tree.binding;
this.checkVisit_(binding.type == BINDING_IDENTIFIER || binding.type == OBJECT_PATTERN || binding.type == ARRAY_PATTERN, binding, 'expected valid binding element');
this.visitAny(tree.initializer);
},
visitAssignmentElement: function(tree) {
var assignment = tree.assignment;
this.checkVisit_(assignment.type == OBJECT_PATTERN || assignment.type == ARRAY_PATTERN || assignment.isLeftHandSideExpression(), assignment, 'expected valid assignment element');
this.visitAny(tree.initializer);
},
visitBlock: function(tree) {
for (var i = 0; i < tree.statements.length; i++) {
var statement = tree.statements[i];
this.checkVisit_(statement.isStatementListItem(), statement, 'statement or function declaration expected');
}
},
visitCallExpression: function(tree) {
this.check_(tree.operand.isMemberExpression(), tree.operand, 'member expression expected');
if (tree.operand instanceof NewExpression) {
this.check_(tree.operand.args !== null, tree.operand, 'new args expected');
}
this.visitAny(tree.operand);
this.visitAny(tree.args);
},
visitCaseClause: function(tree) {
this.checkVisit_(tree.expression.isExpression(), tree.expression, 'expression expected');
for (var i = 0; i < tree.statements.length; i++) {
var statement = tree.statements[i];
this.checkVisit_(statement.isStatement(), statement, 'statement expected');
}
},
visitCatch: function(tree) {
this.checkVisit_(tree.binding.isPattern() || tree.binding.type == BINDING_IDENTIFIER, tree.binding, 'binding identifier expected');
this.checkVisit_(tree.catchBody.type === BLOCK, tree.catchBody, 'block expected');
},
visitClassDeclaration: function(tree) {
for (var i = 0; i < tree.elements.length; i++) {
var element = tree.elements[i];
switch (element.type) {
case GET_ACCESSOR:
case SET_ACCESSOR:
case PROPERTY_METHOD_ASSIGNMENT:
break;
default:
this.fail_(element, 'class element expected');
}
this.visitAny(element);
}
},
visitCommaExpression: function(tree) {
for (var i = 0; i < tree.expressions.length; i++) {
var expression = tree.expressions[i];
this.checkVisit_(expression.isAssignmentExpression(), expression, 'expression expected');
}
},
visitConditionalExpression: function(tree) {
this.checkVisit_(tree.condition.isAssignmentExpression(), tree.condition, 'expression expected');
this.checkVisit_(tree.left.isAssignmentExpression(), tree.left, 'expression expected');
this.checkVisit_(tree.right.isAssignmentExpression(), tree.right, 'expression expected');
},
visitCoverFormals: function(tree) {
this.fail_(tree, 'CoverFormals should have been removed');
},
visitCoverInitializedName: function(tree) {
this.fail_(tree, 'CoverInitializedName should have been removed');
},
visitDefaultClause: function(tree) {
for (var i = 0; i < tree.statements.length; i++) {
var statement = tree.statements[i];
this.checkVisit_(statement.isStatement(), statement, 'statement expected');
}
},
visitDoWhileStatement: function(tree) {
this.checkVisit_(tree.body.isStatement(), tree.body, 'statement expected');
this.checkVisit_(tree.condition.isExpression(), tree.condition, 'expression expected');
},
visitExportDeclaration: function(tree) {
var declType = tree.declaration.type;
this.checkVisit_(declType == VARIABLE_STATEMENT || declType == FUNCTION_DECLARATION || declType == MODULE_DECLARATION || declType == CLASS_DECLARATION || declType == NAMED_EXPORT || declType == EXPORT_DEFAULT, tree.declaration, 'expected valid export tree');
},
visitNamedExport: function(tree) {
if (tree.moduleSpecifier) {
this.checkVisit_(tree.moduleSpecifier.type == MODULE_SPECIFIER, tree.moduleSpecifier, 'module expression expected');
}
var specifierType = tree.specifierSet.type;
this.checkVisit_(specifierType == EXPORT_SPECIFIER_SET || specifierType == EXPORT_STAR, tree.specifierSet, 'specifier set or identifier expected');
},
visitExportSpecifierSet: function(tree) {
this.check_(tree.specifiers.length > 0, tree, 'expected at least one identifier');
for (var i = 0; i < tree.specifiers.length; i++) {
var specifier = tree.specifiers[i];
this.checkVisit_(specifier.type == EXPORT_SPECIFIER || specifier.type == IDENTIFIER_EXPRESSION, specifier, 'expected valid export specifier');
}
},
visitExpressionStatement: function(tree) {
this.checkVisit_(tree.expression.isExpression(), tree.expression, 'expression expected');
},
visitFinally: function(tree) {
this.checkVisit_(tree.block.type === BLOCK, tree.block, 'block expected');
},
visitForOfStatement: function(tree) {
this.checkVisit_(tree.initializer.isPattern() || tree.initializer.type === IDENTIFIER_EXPRESSION || tree.initializer.type === VARIABLE_DECLARATION_LIST && tree.initializer.declarations.length === 1, tree.initializer, 'for-each statement may not have more than one variable declaration');
this.checkVisit_(tree.collection.isExpression(), tree.collection, 'expression expected');
this.checkVisit_(tree.body.isStatement(), tree.body, 'statement expected');
},
visitForInStatement: function(tree) {
if (tree.initializer.type === VARIABLE_DECLARATION_LIST) {
this.checkVisit_(tree.initializer.declarations.length <= 1, tree.initializer, 'for-in statement may not have more than one variable declaration');
} else {
this.checkVisit_(tree.initializer.isPattern() || tree.initializer.isExpression(), tree.initializer, 'variable declaration, expression or ' + 'pattern expected');
}
this.checkVisit_(tree.collection.isExpression(), tree.collection, 'expression expected');
this.checkVisit_(tree.body.isStatement(), tree.body, 'statement expected');
},
visitFormalParameterList: function(tree) {
for (var i = 0; i < tree.parameters.length; i++) {
var parameter = tree.parameters[i];
assert(parameter.type === FORMAL_PARAMETER);
parameter = parameter.parameter;
switch (parameter.type) {
case BINDING_ELEMENT:
break;
case REST_PARAMETER:
this.checkVisit_(i === tree.parameters.length - 1, parameter, 'rest parameters must be the last parameter in a parameter list');
this.checkType_(BINDING_IDENTIFIER, parameter.identifier, 'binding identifier expected');
break;
default:
this.fail_(parameter, 'parameters must be identifiers or rest' + (" parameters. Found: " + parameter.type));
break;
}
this.visitAny(parameter);
}
},
visitForStatement: function(tree) {
if (tree.initializer !== null) {
this.checkVisit_(tree.initializer.isExpression() || tree.initializer.type === VARIABLE_DECLARATION_LIST, tree.initializer, 'variable declaration list or expression expected');
}
if (tree.condition !== null) {
this.checkVisit_(tree.condition.isExpression(), tree.condition, 'expression expected');
}
if (tree.increment !== null) {
this.checkVisit_(tree.increment.isExpression(), tree.increment, 'expression expected');
}
this.checkVisit_(tree.body.isStatement(), tree.body, 'statement expected');
},
visitFunctionBody: function(tree) {
for (var i = 0; i < tree.statements.length; i++) {
var statement = tree.statements[i];
this.checkVisit_(statement.isStatementListItem(), statement, 'statement expected');
}
},
visitFunctionDeclaration: function(tree) {
this.checkType_(BINDING_IDENTIFIER, tree.name, 'binding identifier expected');
this.visitFunction_(tree);
},
visitFunctionExpression: function(tree) {
if (tree.name !== null) {
this.checkType_(BINDING_IDENTIFIER, tree.name, 'binding identifier expected');
}
this.visitFunction_(tree);
},
visitFunction_: function(tree) {
this.checkType_(FORMAL_PARAMETER_LIST, tree.parameterList, 'formal parameters expected');
this.checkType_(FUNCTION_BODY, tree.body, 'function body expected');
},
visitGetAccessor: function(tree) {
this.checkPropertyName_(tree.name);
this.checkType_(FUNCTION_BODY, tree.body, 'function body expected');
},
visitIfStatement: function(tree) {
this.checkVisit_(tree.condition.isExpression(), tree.condition, 'expression expected');
this.checkVisit_(tree.ifClause.isStatement(), tree.ifClause, 'statement expected');
if (tree.elseClause !== null) {
this.checkVisit_(tree.elseClause.isStatement(), tree.elseClause, 'statement expected');
}
},
visitLabelledStatement: function(tree) {
this.checkVisit_(tree.statement.isStatement(), tree.statement, 'statement expected');
},
visitMemberExpression: function(tree) {
this.check_(tree.operand.isMemberExpression(), tree.operand, 'member expression expected');
if (tree.operand instanceof NewExpression) {
this.check_(tree.operand.args !== null, tree.operand, 'new args expected');
}
this.visitAny(tree.operand);
},
visitMemberLookupExpression: function(tree) {
this.check_(tree.operand.isMemberExpression(), tree.operand, 'member expression expected');
if (tree.operand instanceof NewExpression) {
this.check_(tree.operand.args !== null, tree.operand, 'new args expected');
}
this.visitAny(tree.operand);
},
visitSyntaxErrorTree: function(tree) {
this.fail_(tree, ("parse tree contains SyntaxError: " + tree.message));
},
visitModuleSpecifier: function(tree) {
this.check_(tree.token.type == STRING || tree.moduleName, 'string or identifier expected');
},
visitModuleDeclaration: function(tree) {
this.checkType_(MODULE_SPECIFIER, tree.expression, 'module expression expected');
},
visitNewExpression: function(tree) {
this.checkVisit_(tree.operand.isMemberExpression(), tree.operand, 'member expression expected');
this.visitAny(tree.args);
},
visitObjectLiteralExpression: function(tree) {
for (var i = 0; i < tree.propertyNameAndValues.length; i++) {
var propertyNameAndValue = tree.propertyNameAndValues[i];
switch (propertyNameAndValue.type) {
case GET_ACCESSOR:
case SET_ACCESSOR:
case PROPERTY_METHOD_ASSIGNMENT:
this.check_(!propertyNameAndValue.isStatic, propertyNameAndValue, 'static is not allowed in object literal expression');
case PROPERTY_NAME_ASSIGNMENT:
case PROPERTY_NAME_SHORTHAND:
break;
default:
this.fail_(propertyNameAndValue, 'accessor, property name ' + 'assignment or property method assigment expected');
}
this.visitAny(propertyNameAndValue);
}
},
visitObjectPattern: function(tree) {
for (var i = 0; i < tree.fields.length; i++) {
var field = tree.fields[i];
this.checkVisit_(field.type === OBJECT_PATTERN_FIELD || field.type === ASSIGNMENT_ELEMENT || field.type === BINDING_ELEMENT, field, 'object pattern field expected');
}
},
visitObjectPatternField: function(tree) {
this.checkPropertyName_(tree.name);
this.checkVisit_(tree.element.type === ASSIGNMENT_ELEMENT || tree.element.type === BINDING_ELEMENT || tree.element.isPattern() || tree.element.isLeftHandSideExpression(), tree.element, 'binding element expected');
},
visitParenExpression: function(tree) {
if (tree.expression.isPattern()) {
this.visitAny(tree.expression);
} else {
this.checkVisit_(tree.expression.isExpression(), tree.expression, 'expression expected');
}
},
visitPostfixExpression: function(tree) {
this.checkVisit_(tree.operand.isAssignmentExpression(), tree.operand, 'assignment expression expected');
},
visitPredefinedType: function(tree) {},
visitScript: function(tree) {
for (var i = 0; i < tree.scriptItemList.length; i++) {
var scriptItemList = tree.scriptItemList[i];
this.checkVisit_(scriptItemList.isScriptElement(), scriptItemList, 'global script item expected');
}
},
checkPropertyName_: function(tree) {
this.checkVisit_(tree.type === LITERAL_PROPERTY_NAME || tree.type === COMPUTED_PROPERTY_NAME, tree, 'property name expected');
},
visitPropertyNameAssignment: function(tree) {
this.checkPropertyName_(tree.name);
this.checkVisit_(tree.value.isAssignmentExpression(), tree.value, 'assignment expression expected');
},
visitPropertyNameShorthand: function(tree) {
this.check_(tree.name.type === IDENTIFIER, tree, 'identifier token expected');
},
visitLiteralPropertyName: function(tree) {
var type = tree.literalToken.type;
this.check_(tree.literalToken.isKeyword() || type === IDENTIFIER || type === NUMBER || type === STRING, tree, 'Unexpected token in literal property name');
},
visitTemplateLiteralExpression: function(tree) {
if (tree.operand) {
this.checkVisit_(tree.operand.isMemberExpression(), tree.operand, 'member or call expression expected');
}
for (var i = 0; i < tree.elements.length; i++) {
var element = tree.elements[i];
if (i % 2) {
this.checkType_(TEMPLATE_SUBSTITUTION, element, 'Template literal substitution expected');
} else {
this.checkType_(TEMPLATE_LITERAL_PORTION, element, 'Template literal portion expected');
}
}
},
visitReturnStatement: function(tree) {
if (tree.expression !== null) {
this.checkVisit_(tree.expression.isExpression(), tree.expression, 'expression expected');
}
},
visitSetAccessor: function(tree) {
this.checkPropertyName_(tree.name);
this.checkType_(FUNCTION_BODY, tree.body, 'function body expected');
},
visitSpreadExpression: function(tree) {
this.checkVisit_(tree.expression.isAssignmentExpression(), tree.expression, 'assignment expression expected');
},
visitStateMachine: function(tree) {
this.fail_(tree, 'State machines are never valid outside of the ' + 'GeneratorTransformer pass.');
},
visitSwitchStatement: function(tree) {
this.checkVisit_(tree.expression.isExpression(), tree.expression, 'expression expected');
var defaultCount = 0;
for (var i = 0; i < tree.caseClauses.length; i++) {
var caseClause = tree.caseClauses[i];
if (caseClause.type === DEFAULT_CLAUSE) {
++defaultCount;
this.checkVisit_(defaultCount <= 1, caseClause, 'no more than one default clause allowed');
} else {
this.checkType_(CASE_CLAUSE, caseClause, 'case or default clause expected');
}
}
},
visitThrowStatement: function(tree) {
if (tree.value === null) {
return;
}
this.checkVisit_(tree.value.isExpression(), tree.value, 'expression expected');
},
visitTryStatement: function(tree) {
this.checkType_(BLOCK, tree.body, 'block expected');
if (tree.catchBlock !== null) {
this.checkType_(CATCH, tree.catchBlock, 'catch block expected');
}
if (tree.finallyBlock !== null) {
this.checkType_(FINALLY, tree.finallyBlock, 'finally block expected');
}
if (tree.catchBlock === null && tree.finallyBlock === null) {
this.fail_(tree, 'either catch or finally must be present');
}
},
visitTypeName: function(tree) {},
visitUnaryExpression: function(tree) {
this.checkVisit_(tree.operand.isAssignmentExpression(), tree.operand, 'assignment expression expected');
},
visitVariableDeclaration: function(tree) {
this.checkVisit_(tree.lvalue.isPattern() || tree.lvalue.type == BINDING_IDENTIFIER, tree.lvalue, 'binding identifier expected, found: ' + tree.lvalue.type);
if (tree.initializer !== null) {
this.checkVisit_(tree.initializer.isAssignmentExpression(), tree.initializer, 'assignment expression expected');
}
},
visitWhileStatement: function(tree) {
this.checkVisit_(tree.condition.isExpression(), tree.condition, 'expression expected');
this.checkVisit_(tree.body.isStatement(), tree.body, 'statement expected');
},
visitWithStatement: function(tree) {
this.checkVisit_(tree.expression.isExpression(), tree.expression, 'expression expected');
this.checkVisit_(tree.body.isStatement(), tree.body, 'statement expected');
},
visitYieldExpression: function(tree) {
if (tree.expression !== null) {
this.checkVisit_(tree.expression.isExpression(), tree.expression, 'expression expected');
}
}
}, {}, ParseTreeVisitor);
ParseTreeValidator.validate = function(tree) {
var validator = new ParseTreeValidator();
try {
validator.visitAny(tree);
} catch (e) {
if (!(e instanceof ValidationError)) {
throw e;
}
var location = null;
if (e.tree !== null) {
location = e.tree.location;
}
if (location === null) {
location = tree.location;
}
var locationString = location !== null ? location.start.toString() : '(unknown)';
throw new Error(("Parse tree validation failure '" + e.message + "' at " + locationString + ":") + '\n\n' + TreeWriter.write(tree, {
highlighted: e.tree,
showLineNumbers: true
}) + '\n');
}
};
return {get ParseTreeValidator() {
return ParseTreeValidator;
}};
});
System.register("traceur@0.0.52/src/codegeneration/MultiTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/MultiTransformer";
var ParseTreeValidator = System.get("traceur@0.0.52/src/syntax/ParseTreeValidator").ParseTreeValidator;
var MultiTransformer = function MultiTransformer(reporter, validate) {
this.reporter_ = reporter;
this.validate_ = validate;
this.treeTransformers_ = [];
};
($traceurRuntime.createClass)(MultiTransformer, {
append: function(treeTransformer) {
this.treeTransformers_.push(treeTransformer);
},
transform: function(tree) {
var reporter = this.reporter_;
var validate = this.validate_;
this.treeTransformers_.every((function(transformTree) {
tree = transformTree(tree);
if (reporter.hadError())
return false;
if (validate)
ParseTreeValidator.validate(tree);
return true;
}));
return tree;
}
}, {});
return {get MultiTransformer() {
return MultiTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/NumericLiteralTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/NumericLiteralTransformer";
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__624 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
LiteralExpression = $__624.LiteralExpression,
LiteralPropertyName = $__624.LiteralPropertyName;
var LiteralToken = System.get("traceur@0.0.52/src/syntax/LiteralToken").LiteralToken;
var NUMBER = System.get("traceur@0.0.52/src/syntax/TokenType").NUMBER;
function needsTransform(token) {
return token.type === NUMBER && /^0[bBoO]/.test(token.value);
}
function transformToken(token) {
return new LiteralToken(NUMBER, String(token.processedValue), token.location);
}
var NumericLiteralTransformer = function NumericLiteralTransformer() {
$traceurRuntime.defaultSuperCall(this, $NumericLiteralTransformer.prototype, arguments);
};
var $NumericLiteralTransformer = NumericLiteralTransformer;
($traceurRuntime.createClass)(NumericLiteralTransformer, {
transformLiteralExpression: function(tree) {
var token = tree.literalToken;
if (needsTransform(token))
return new LiteralExpression(tree.location, transformToken(token));
return tree;
},
transformLiteralPropertyName: function(tree) {
var token = tree.literalToken;
if (needsTransform(token))
return new LiteralPropertyName(tree.location, transformToken(token));
return tree;
}
}, {}, ParseTreeTransformer);
return {get NumericLiteralTransformer() {
return NumericLiteralTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/ObjectLiteralTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/ObjectLiteralTransformer";
var FindVisitor = System.get("traceur@0.0.52/src/codegeneration/FindVisitor").FindVisitor;
var $__629 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
FunctionExpression = $__629.FunctionExpression,
IdentifierExpression = $__629.IdentifierExpression,
LiteralExpression = $__629.LiteralExpression;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var IDENTIFIER = System.get("traceur@0.0.52/src/syntax/TokenType").IDENTIFIER;
var $__632 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
COMPUTED_PROPERTY_NAME = $__632.COMPUTED_PROPERTY_NAME,
LITERAL_PROPERTY_NAME = $__632.LITERAL_PROPERTY_NAME;
var $__633 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createAssignmentExpression = $__633.createAssignmentExpression,
createCommaExpression = $__633.createCommaExpression,
createDefineProperty = $__633.createDefineProperty,
createEmptyParameterList = $__633.createEmptyParameterList,
createFunctionExpression = $__633.createFunctionExpression,
createIdentifierExpression = $__633.createIdentifierExpression,
createObjectCreate = $__633.createObjectCreate,
createObjectLiteralExpression = $__633.createObjectLiteralExpression,
createParenExpression = $__633.createParenExpression,
createPropertyNameAssignment = $__633.createPropertyNameAssignment,
createStringLiteral = $__633.createStringLiteral;
var propName = System.get("traceur@0.0.52/src/staticsemantics/PropName").propName;
var transformOptions = System.get("traceur@0.0.52/src/Options").transformOptions;
var FindAdvancedProperty = function FindAdvancedProperty(tree) {
this.protoExpression = null;
$traceurRuntime.superCall(this, $FindAdvancedProperty.prototype, "constructor", [tree, true]);
};
var $FindAdvancedProperty = FindAdvancedProperty;
($traceurRuntime.createClass)(FindAdvancedProperty, {
visitPropertyNameAssignment: function(tree) {
if (isProtoName(tree.name))
this.protoExpression = tree.value;
else
$traceurRuntime.superCall(this, $FindAdvancedProperty.prototype, "visitPropertyNameAssignment", [tree]);
},
visitComputedPropertyName: function(tree) {
if (transformOptions.computedPropertyNames)
this.found = true;
}
}, {}, FindVisitor);
function isProtoName(tree) {
return propName(tree) === '__proto__';
}
var ObjectLiteralTransformer = function ObjectLiteralTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $ObjectLiteralTransformer.prototype, "constructor", [identifierGenerator]);
this.protoExpression = null;
this.needsAdvancedTransform = false;
this.seenAccessors = null;
};
var $ObjectLiteralTransformer = ObjectLiteralTransformer;
($traceurRuntime.createClass)(ObjectLiteralTransformer, {
findSeenAccessor_: function(name) {
if (name.type === COMPUTED_PROPERTY_NAME)
return null;
var s = propName(name);
return this.seenAccessors[s];
},
removeSeenAccessor_: function(name) {
if (name.type === COMPUTED_PROPERTY_NAME)
return;
var s = propName(name);
delete this.seenAccessors[s];
},
addSeenAccessor_: function(name, descr) {
if (name.type === COMPUTED_PROPERTY_NAME)
return;
var s = propName(name);
this.seenAccessors[s] = descr;
},
createProperty_: function(name, descr) {
var expression;
if (name.type === LITERAL_PROPERTY_NAME) {
if (this.needsAdvancedTransform)
expression = this.getPropertyName_(name);
else
expression = name;
} else {
expression = name.expression;
}
if (descr.get || descr.set) {
var oldAccessor = this.findSeenAccessor_(name);
if (oldAccessor) {
oldAccessor.get = descr.get || oldAccessor.get;
oldAccessor.set = descr.set || oldAccessor.set;
this.removeSeenAccessor_(name);
return null;
} else {
this.addSeenAccessor_(name, descr);
}
}
return [expression, descr];
},
getPropertyName_: function(nameTree) {
var token = nameTree.literalToken;
switch (token.type) {
case IDENTIFIER:
return createStringLiteral(token.value);
default:
if (token.isKeyword())
return createStringLiteral(token.type);
return new LiteralExpression(token.location, token);
}
},
transformClassDeclaration: function(tree) {
return tree;
},
transformClassExpression: function(tree) {
return tree;
},
transformObjectLiteralExpression: function(tree) {
var oldNeedsTransform = this.needsAdvancedTransform;
var oldSeenAccessors = this.seenAccessors;
try {
var finder = new FindAdvancedProperty(tree);
if (!finder.found) {
this.needsAdvancedTransform = false;
return $traceurRuntime.superCall(this, $ObjectLiteralTransformer.prototype, "transformObjectLiteralExpression", [tree]);
}
this.needsAdvancedTransform = true;
this.seenAccessors = Object.create(null);
var properties = this.transformList(tree.propertyNameAndValues);
properties = properties.filter((function(tree) {
return tree;
}));
var tempVar = this.addTempVar();
var tempVarIdentifierExpression = createIdentifierExpression(tempVar);
var expressions = properties.map((function(property) {
var expression = property[0];
var descr = property[1];
return createDefineProperty(tempVarIdentifierExpression, expression, descr);
}));
var protoExpression = this.transformAny(finder.protoExpression);
var objectExpression;
if (protoExpression)
objectExpression = createObjectCreate(protoExpression);
else
objectExpression = createObjectLiteralExpression([]);
expressions.unshift(createAssignmentExpression(tempVarIdentifierExpression, objectExpression));
expressions.push(tempVarIdentifierExpression);
return createParenExpression(createCommaExpression(expressions));
} finally {
this.needsAdvancedTransform = oldNeedsTransform;
this.seenAccessors = oldSeenAccessors;
}
},
transformPropertyNameAssignment: function(tree) {
if (!this.needsAdvancedTransform)
return $traceurRuntime.superCall(this, $ObjectLiteralTransformer.prototype, "transformPropertyNameAssignment", [tree]);
if (isProtoName(tree.name))
return null;
return this.createProperty_(tree.name, {
value: this.transformAny(tree.value),
configurable: true,
enumerable: true,
writable: true
});
},
transformGetAccessor: function(tree) {
if (!this.needsAdvancedTransform)
return $traceurRuntime.superCall(this, $ObjectLiteralTransformer.prototype, "transformGetAccessor", [tree]);
var body = this.transformAny(tree.body);
var func = createFunctionExpression(createEmptyParameterList(), body);
return this.createProperty_(tree.name, {
get: func,
configurable: true,
enumerable: true
});
},
transformSetAccessor: function(tree) {
if (!this.needsAdvancedTransform)
return $traceurRuntime.superCall(this, $ObjectLiteralTransformer.prototype, "transformSetAccessor", [tree]);
var body = this.transformAny(tree.body);
var parameterList = this.transformAny(tree.parameterList);
var func = createFunctionExpression(parameterList, body);
return this.createProperty_(tree.name, {
set: func,
configurable: true,
enumerable: true
});
},
transformPropertyMethodAssignment: function(tree) {
var func = new FunctionExpression(tree.location, null, tree.functionKind, this.transformAny(tree.parameterList), tree.typeAnnotation, [], this.transformAny(tree.body));
if (!this.needsAdvancedTransform) {
return createPropertyNameAssignment(tree.name, func);
}
var expression = this.transformAny(tree.name);
return this.createProperty_(tree.name, {
value: func,
configurable: true,
enumerable: true,
writable: true
});
},
transformPropertyNameShorthand: function(tree) {
if (!this.needsAdvancedTransform)
return $traceurRuntime.superCall(this, $ObjectLiteralTransformer.prototype, "transformPropertyNameShorthand", [tree]);
var expression = this.transformAny(tree.name);
return this.createProperty_(tree.name, {
value: new IdentifierExpression(tree.location, tree.name.identifierToken),
configurable: true,
enumerable: false,
writable: true
});
}
}, {}, TempVarTransformer);
return {get ObjectLiteralTransformer() {
return ObjectLiteralTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/PropertyNameShorthandTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/PropertyNameShorthandTransformer";
var $__637 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
IdentifierExpression = $__637.IdentifierExpression,
LiteralPropertyName = $__637.LiteralPropertyName,
PropertyNameAssignment = $__637.PropertyNameAssignment;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var PropertyNameShorthandTransformer = function PropertyNameShorthandTransformer() {
$traceurRuntime.defaultSuperCall(this, $PropertyNameShorthandTransformer.prototype, arguments);
};
var $PropertyNameShorthandTransformer = PropertyNameShorthandTransformer;
($traceurRuntime.createClass)(PropertyNameShorthandTransformer, {transformPropertyNameShorthand: function(tree) {
return new PropertyNameAssignment(tree.location, new LiteralPropertyName(tree.location, tree.name), new IdentifierExpression(tree.location, tree.name));
}}, {}, ParseTreeTransformer);
return {get PropertyNameShorthandTransformer() {
return PropertyNameShorthandTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/RestParameterTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/RestParameterTransformer";
var $__640 = Object.freeze(Object.defineProperties(["\n for (var ", " = [], ", " = ", ";\n ", " < arguments.length; ", "++)\n ", "[", " - ", "] = arguments[", "];"], {raw: {value: Object.freeze(["\n for (var ", " = [], ", " = ", ";\n ", " < arguments.length; ", "++)\n ", "[", " - ", "] = arguments[", "];"])}})),
$__641 = Object.freeze(Object.defineProperties(["\n for (var ", " = [], ", " = 0;\n ", " < arguments.length; ", "++)\n ", "[", "] = arguments[", "];"], {raw: {value: Object.freeze(["\n for (var ", " = [], ", " = 0;\n ", " < arguments.length; ", "++)\n ", "[", "] = arguments[", "];"])}}));
var FormalParameterList = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").FormalParameterList;
var ParameterTransformer = System.get("traceur@0.0.52/src/codegeneration/ParameterTransformer").ParameterTransformer;
var createIdentifierToken = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createIdentifierToken;
var parseStatement = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatement;
function hasRestParameter(parameterList) {
var parameters = parameterList.parameters;
return parameters.length > 0 && parameters[parameters.length - 1].isRestParameter();
}
function getRestParameterLiteralToken(parameterList) {
var parameters = parameterList.parameters;
return parameters[parameters.length - 1].parameter.identifier.identifierToken;
}
var RestParameterTransformer = function RestParameterTransformer() {
$traceurRuntime.defaultSuperCall(this, $RestParameterTransformer.prototype, arguments);
};
var $RestParameterTransformer = RestParameterTransformer;
($traceurRuntime.createClass)(RestParameterTransformer, {transformFormalParameterList: function(tree) {
var transformed = $traceurRuntime.superCall(this, $RestParameterTransformer.prototype, "transformFormalParameterList", [tree]);
if (hasRestParameter(transformed)) {
var parametersWithoutRestParam = new FormalParameterList(transformed.location, transformed.parameters.slice(0, -1));
var startIndex = transformed.parameters.length - 1;
var i = createIdentifierToken(this.getTempIdentifier());
var name = getRestParameterLiteralToken(transformed);
var loop;
if (startIndex) {
loop = parseStatement($__640, name, i, startIndex, i, i, name, i, startIndex, i);
} else {
loop = parseStatement($__641, name, i, i, i, name, i, i);
}
this.parameterStatements.push(loop);
return parametersWithoutRestParam;
}
return transformed;
}}, {}, ParameterTransformer);
return {get RestParameterTransformer() {
return RestParameterTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/SpreadTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/SpreadTransformer";
var $__647 = Object.freeze(Object.defineProperties(["$traceurRuntime.spread(", ")"], {raw: {value: Object.freeze(["$traceurRuntime.spread(", ")"])}}));
var $__648 = System.get("traceur@0.0.52/src/syntax/PredefinedName"),
APPLY = $__648.APPLY,
BIND = $__648.BIND,
FUNCTION = $__648.FUNCTION,
PROTOTYPE = $__648.PROTOTYPE;
var $__649 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
MEMBER_EXPRESSION = $__649.MEMBER_EXPRESSION,
MEMBER_LOOKUP_EXPRESSION = $__649.MEMBER_LOOKUP_EXPRESSION,
SPREAD_EXPRESSION = $__649.SPREAD_EXPRESSION;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__651 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArgumentList = $__651.createArgumentList,
createArrayLiteralExpression = $__651.createArrayLiteralExpression,
createAssignmentExpression = $__651.createAssignmentExpression,
createCallExpression = $__651.createCallExpression,
createEmptyArgumentList = $__651.createEmptyArgumentList,
createIdentifierExpression = $__651.createIdentifierExpression,
createMemberExpression = $__651.createMemberExpression,
createMemberLookupExpression = $__651.createMemberLookupExpression,
createNewExpression = $__651.createNewExpression,
createNullLiteral = $__651.createNullLiteral,
createParenExpression = $__651.createParenExpression;
var parseExpression = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseExpression;
function hasSpreadMember(trees) {
return trees.some((function(tree) {
return tree && tree.type == SPREAD_EXPRESSION;
}));
}
var SpreadTransformer = function SpreadTransformer() {
$traceurRuntime.defaultSuperCall(this, $SpreadTransformer.prototype, arguments);
};
var $SpreadTransformer = SpreadTransformer;
($traceurRuntime.createClass)(SpreadTransformer, {
createArrayFromElements_: function(elements) {
var length = elements.length;
var args = [];
var lastArray;
for (var i = 0; i < length; i++) {
if (elements[i] && elements[i].type === SPREAD_EXPRESSION) {
if (lastArray) {
args.push(createArrayLiteralExpression(lastArray));
lastArray = null;
}
args.push(this.transformAny(elements[i].expression));
} else {
if (!lastArray)
lastArray = [];
lastArray.push(this.transformAny(elements[i]));
}
}
if (lastArray)
args.push(createArrayLiteralExpression(lastArray));
return parseExpression($__647, createArgumentList(args));
},
desugarCallSpread_: function(tree) {
var operand = this.transformAny(tree.operand);
var functionObject,
contextObject;
this.pushTempScope();
if (operand.type == MEMBER_EXPRESSION) {
var tempIdent = createIdentifierExpression(this.addTempVar());
var parenExpression = createParenExpression(createAssignmentExpression(tempIdent, operand.operand));
var memberName = operand.memberName;
contextObject = tempIdent;
functionObject = createMemberExpression(parenExpression, memberName);
} else if (tree.operand.type == MEMBER_LOOKUP_EXPRESSION) {
var tempIdent = createIdentifierExpression(this.addTempVar());
var parenExpression = createParenExpression(createAssignmentExpression(tempIdent, operand.operand));
var memberExpression = this.transformAny(operand.memberExpression);
contextObject = tempIdent;
functionObject = createMemberLookupExpression(parenExpression, memberExpression);
} else {
contextObject = createNullLiteral();
functionObject = operand;
}
this.popTempScope();
var arrayExpression = this.createArrayFromElements_(tree.args.args);
return createCallExpression(createMemberExpression(functionObject, APPLY), createArgumentList([contextObject, arrayExpression]));
},
desugarNewSpread_: function(tree) {
var arrayExpression = $traceurRuntime.spread([createNullLiteral()], tree.args.args);
arrayExpression = this.createArrayFromElements_(arrayExpression);
return createNewExpression(createParenExpression(createCallExpression(createMemberExpression(FUNCTION, PROTOTYPE, BIND, APPLY), createArgumentList([this.transformAny(tree.operand), arrayExpression]))), createEmptyArgumentList());
},
transformArrayLiteralExpression: function(tree) {
if (hasSpreadMember(tree.elements)) {
return this.createArrayFromElements_(tree.elements);
}
return $traceurRuntime.superCall(this, $SpreadTransformer.prototype, "transformArrayLiteralExpression", [tree]);
},
transformCallExpression: function(tree) {
if (hasSpreadMember(tree.args.args)) {
return this.desugarCallSpread_(tree);
}
return $traceurRuntime.superCall(this, $SpreadTransformer.prototype, "transformCallExpression", [tree]);
},
transformNewExpression: function(tree) {
if (tree.args != null && hasSpreadMember(tree.args.args)) {
return this.desugarNewSpread_(tree);
}
return $traceurRuntime.superCall(this, $SpreadTransformer.prototype, "transformNewExpression", [tree]);
}
}, {}, TempVarTransformer);
return {get SpreadTransformer() {
return SpreadTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/SymbolTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/SymbolTransformer";
var $__654 = Object.freeze(Object.defineProperties(["$traceurRuntime.toProperty(", ") in ", ""], {raw: {value: Object.freeze(["$traceurRuntime.toProperty(", ") in ", ""])}})),
$__655 = Object.freeze(Object.defineProperties(["$traceurRuntime.setProperty(", ",\n ", ", ", ")"], {raw: {value: Object.freeze(["$traceurRuntime.setProperty(", ",\n ", ", ", ")"])}})),
$__656 = Object.freeze(Object.defineProperties(["", "[$traceurRuntime.toProperty(", ")]"], {raw: {value: Object.freeze(["", "[$traceurRuntime.toProperty(", ")]"])}})),
$__657 = Object.freeze(Object.defineProperties(["$traceurRuntime.typeof(", ")"], {raw: {value: Object.freeze(["$traceurRuntime.typeof(", ")"])}})),
$__658 = Object.freeze(Object.defineProperties(["(typeof ", " === 'undefined' ?\n 'undefined' : ", ")"], {raw: {value: Object.freeze(["(typeof ", " === 'undefined' ?\n 'undefined' : ", ")"])}}));
var $__659 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
BinaryExpression = $__659.BinaryExpression,
MemberLookupExpression = $__659.MemberLookupExpression,
UnaryExpression = $__659.UnaryExpression;
var ExplodeExpressionTransformer = System.get("traceur@0.0.52/src/codegeneration/ExplodeExpressionTransformer").ExplodeExpressionTransformer;
var $__661 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
IDENTIFIER_EXPRESSION = $__661.IDENTIFIER_EXPRESSION,
LITERAL_EXPRESSION = $__661.LITERAL_EXPRESSION,
MEMBER_LOOKUP_EXPRESSION = $__661.MEMBER_LOOKUP_EXPRESSION,
UNARY_EXPRESSION = $__661.UNARY_EXPRESSION;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__663 = System.get("traceur@0.0.52/src/syntax/TokenType"),
EQUAL = $__663.EQUAL,
EQUAL_EQUAL = $__663.EQUAL_EQUAL,
EQUAL_EQUAL_EQUAL = $__663.EQUAL_EQUAL_EQUAL,
IN = $__663.IN,
NOT_EQUAL = $__663.NOT_EQUAL,
NOT_EQUAL_EQUAL = $__663.NOT_EQUAL_EQUAL,
STRING = $__663.STRING,
TYPEOF = $__663.TYPEOF;
var createParenExpression = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory").createParenExpression;
var parseExpression = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseExpression;
var ExplodeSymbolExpression = function ExplodeSymbolExpression() {
$traceurRuntime.defaultSuperCall(this, $ExplodeSymbolExpression.prototype, arguments);
};
var $ExplodeSymbolExpression = ExplodeSymbolExpression;
($traceurRuntime.createClass)(ExplodeSymbolExpression, {
transformArrowFunctionExpression: function(tree) {
return tree;
},
transformClassExpression: function(tree) {
return tree;
},
transformFunctionBody: function(tree) {
return tree;
}
}, {}, ExplodeExpressionTransformer);
function isEqualityExpression(tree) {
switch (tree.operator.type) {
case EQUAL_EQUAL:
case EQUAL_EQUAL_EQUAL:
case NOT_EQUAL:
case NOT_EQUAL_EQUAL:
return true;
}
return false;
}
function isTypeof(tree) {
return tree.type === UNARY_EXPRESSION && tree.operator.type === TYPEOF;
}
function isSafeTypeofString(tree) {
if (tree.type !== LITERAL_EXPRESSION)
return false;
var value = tree.literalToken.processedValue;
switch (value) {
case 'symbol':
case 'object':
return false;
}
return true;
}
var SymbolTransformer = function SymbolTransformer() {
$traceurRuntime.defaultSuperCall(this, $SymbolTransformer.prototype, arguments);
};
var $SymbolTransformer = SymbolTransformer;
($traceurRuntime.createClass)(SymbolTransformer, {
transformTypeofOperand_: function(tree) {
var operand = this.transformAny(tree.operand);
return new UnaryExpression(tree.location, tree.operator, operand);
},
transformBinaryExpression: function(tree) {
if (tree.operator.type === IN) {
var name = this.transformAny(tree.left);
var object = this.transformAny(tree.right);
if (name.type === LITERAL_EXPRESSION)
return new BinaryExpression(tree.location, name, tree.operator, object);
return parseExpression($__654, name, object);
}
if (isEqualityExpression(tree)) {
if (isTypeof(tree.left) && isSafeTypeofString(tree.right)) {
var left = this.transformTypeofOperand_(tree.left);
var right = tree.right;
return new BinaryExpression(tree.location, left, tree.operator, right);
}
if (isTypeof(tree.right) && isSafeTypeofString(tree.left)) {
var left = tree.left;
var right = this.transformTypeofOperand_(tree.right);
return new BinaryExpression(tree.location, left, tree.operator, right);
}
}
if (tree.left.type === MEMBER_LOOKUP_EXPRESSION && tree.operator.isAssignmentOperator()) {
if (tree.operator.type !== EQUAL) {
var exploded = new ExplodeSymbolExpression(this).transformAny(tree);
return this.transformAny(createParenExpression(exploded));
}
var operand = this.transformAny(tree.left.operand);
var memberExpression = this.transformAny(tree.left.memberExpression);
var value = this.transformAny(tree.right);
return parseExpression($__655, operand, memberExpression, value);
}
return $traceurRuntime.superCall(this, $SymbolTransformer.prototype, "transformBinaryExpression", [tree]);
},
transformMemberLookupExpression: function(tree) {
var operand = this.transformAny(tree.operand);
var memberExpression = this.transformAny(tree.memberExpression);
if (memberExpression.type === LITERAL_EXPRESSION && memberExpression.literalToken.type !== STRING) {
return new MemberLookupExpression(tree.location, operand, memberExpression);
}
return parseExpression($__656, operand, memberExpression);
},
transformUnaryExpression: function(tree) {
if (tree.operator.type !== TYPEOF)
return $traceurRuntime.superCall(this, $SymbolTransformer.prototype, "transformUnaryExpression", [tree]);
var operand = this.transformAny(tree.operand);
var expression = parseExpression($__657, operand);
if (operand.type === IDENTIFIER_EXPRESSION) {
return parseExpression($__658, operand, expression);
}
return expression;
}
}, {}, TempVarTransformer);
return {get SymbolTransformer() {
return SymbolTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/TemplateLiteralTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/TemplateLiteralTransformer";
var $__667 = Object.freeze(Object.defineProperties(["Object.freeze(Object.defineProperties(", ", {\n raw: {\n value: Object.freeze(", ")\n }\n }))"], {raw: {value: Object.freeze(["Object.freeze(Object.defineProperties(", ", {\n raw: {\n value: Object.freeze(", ")\n }\n }))"])}}));
var $__668 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BINARY_EXPRESSION = $__668.BINARY_EXPRESSION,
COMMA_EXPRESSION = $__668.COMMA_EXPRESSION,
CONDITIONAL_EXPRESSION = $__668.CONDITIONAL_EXPRESSION,
TEMPLATE_LITERAL_PORTION = $__668.TEMPLATE_LITERAL_PORTION;
var $__669 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
LiteralExpression = $__669.LiteralExpression,
ParenExpression = $__669.ParenExpression;
var LiteralToken = System.get("traceur@0.0.52/src/syntax/LiteralToken").LiteralToken;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var TempVarTransformer = System.get("traceur@0.0.52/src/codegeneration/TempVarTransformer").TempVarTransformer;
var $__673 = System.get("traceur@0.0.52/src/syntax/TokenType"),
PERCENT = $__673.PERCENT,
PLUS = $__673.PLUS,
SLASH = $__673.SLASH,
STAR = $__673.STAR,
STRING = $__673.STRING;
var $__674 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArgumentList = $__674.createArgumentList,
createArrayLiteralExpression = $__674.createArrayLiteralExpression,
createBinaryExpression = $__674.createBinaryExpression,
createCallExpression = $__674.createCallExpression,
createIdentifierExpression = $__674.createIdentifierExpression,
createOperatorToken = $__674.createOperatorToken,
createStringLiteral = $__674.createStringLiteral;
var parseExpression = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseExpression;
function createCallSiteIdObject(tree) {
var elements = tree.elements;
var cooked = createCookedStringArray(elements);
var raw = createRawStringArray(elements);
return parseExpression($__667, cooked, raw);
}
function maybeAddEmptyStringAtEnd(elements, items) {
var length = elements.length;
if (!length || elements[length - 1].type !== TEMPLATE_LITERAL_PORTION)
items.push(createStringLiteral(''));
}
function createRawStringArray(elements) {
var items = [];
for (var i = 0; i < elements.length; i += 2) {
var str = elements[i].value.value;
str = str.replace(/\r\n?/g, '\n');
str = JSON.stringify(str);
str = replaceRaw(str);
var loc = elements[i].location;
var expr = new LiteralExpression(loc, new LiteralToken(STRING, str, loc));
items.push(expr);
}
maybeAddEmptyStringAtEnd(elements, items);
return createArrayLiteralExpression(items);
}
function createCookedStringLiteralExpression(tree) {
var str = cookString(tree.value.value);
var loc = tree.location;
return new LiteralExpression(loc, new LiteralToken(STRING, str, loc));
}
function createCookedStringArray(elements) {
var items = [];
for (var i = 0; i < elements.length; i += 2) {
items.push(createCookedStringLiteralExpression(elements[i]));
}
maybeAddEmptyStringAtEnd(elements, items);
return createArrayLiteralExpression(items);
}
function replaceRaw(s) {
return s.replace(/\u2028|\u2029/g, function(c) {
switch (c) {
case '\u2028':
return '\\u2028';
case '\u2029':
return '\\u2029';
default:
throw Error('Not reachable');
}
});
}
function cookString(s) {
var sb = ['"'];
var i = 0,
k = 1,
c,
c2;
while (i < s.length) {
c = s[i++];
switch (c) {
case '\\':
c2 = s[i++];
switch (c2) {
case '\n':
case '\u2028':
case '\u2029':
break;
case '\r':
if (s[i + 1] === '\n') {
i++;
}
break;
default:
sb[k++] = c;
sb[k++] = c2;
}
break;
case '"':
sb[k++] = '\\"';
break;
case '\n':
sb[k++] = '\\n';
break;
case '\r':
if (s[i] === '\n')
i++;
sb[k++] = '\\n';
break;
case '\t':
sb[k++] = '\\t';
break;
case '\f':
sb[k++] = '\\f';
break;
case '\b':
sb[k++] = '\\b';
break;
case '\u2028':
sb[k++] = '\\u2028';
break;
case '\u2029':
sb[k++] = '\\u2029';
break;
default:
sb[k++] = c;
}
}
sb[k++] = '"';
return sb.join('');
}
var TemplateLiteralTransformer = function TemplateLiteralTransformer() {
$traceurRuntime.defaultSuperCall(this, $TemplateLiteralTransformer.prototype, arguments);
};
var $TemplateLiteralTransformer = TemplateLiteralTransformer;
($traceurRuntime.createClass)(TemplateLiteralTransformer, {
transformFunctionBody: function(tree) {
return ParseTreeTransformer.prototype.transformFunctionBody.call(this, tree);
},
transformTemplateLiteralExpression: function(tree) {
if (!tree.operand)
return this.createDefaultTemplateLiteral(tree);
var operand = this.transformAny(tree.operand);
var elements = tree.elements;
var callsiteIdObject = createCallSiteIdObject(tree);
var idName = this.addTempVar(callsiteIdObject);
var args = [createIdentifierExpression(idName)];
for (var i = 1; i < elements.length; i += 2) {
args.push(this.transformAny(elements[i]));
}
return createCallExpression(operand, createArgumentList(args));
},
transformTemplateSubstitution: function(tree) {
var transformedTree = this.transformAny(tree.expression);
switch (transformedTree.type) {
case BINARY_EXPRESSION:
switch (transformedTree.operator.type) {
case STAR:
case PERCENT:
case SLASH:
return transformedTree;
}
case COMMA_EXPRESSION:
case CONDITIONAL_EXPRESSION:
return new ParenExpression(null, transformedTree);
}
return transformedTree;
},
transformTemplateLiteralPortion: function(tree) {
return createCookedStringLiteralExpression(tree);
},
createDefaultTemplateLiteral: function(tree) {
var length = tree.elements.length;
if (length === 0) {
var loc = tree.location;
return new LiteralExpression(loc, new LiteralToken(STRING, '""', loc));
}
var firstNonEmpty = tree.elements[0].value.value === '' ? -1 : 0;
var binaryExpression = this.transformAny(tree.elements[0]);
if (length == 1)
return binaryExpression;
var plusToken = createOperatorToken(PLUS);
for (var i = 1; i < length; i++) {
var element = tree.elements[i];
if (element.type === TEMPLATE_LITERAL_PORTION) {
if (element.value.value === '')
continue;
else if (firstNonEmpty < 0 && i === 2)
binaryExpression = binaryExpression.right;
}
var transformedTree = this.transformAny(tree.elements[i]);
binaryExpression = createBinaryExpression(binaryExpression, plusToken, transformedTree);
}
return new ParenExpression(null, binaryExpression);
}
}, {}, TempVarTransformer);
return {get TemplateLiteralTransformer() {
return TemplateLiteralTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/TypeAssertionTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/TypeAssertionTransformer";
var $__677 = Object.freeze(Object.defineProperties(["assert.type(", ", ", ")"], {raw: {value: Object.freeze(["assert.type(", ", ", ")"])}})),
$__678 = Object.freeze(Object.defineProperties(["assert.argumentTypes(", ")"], {raw: {value: Object.freeze(["assert.argumentTypes(", ")"])}})),
$__679 = Object.freeze(Object.defineProperties(["return assert.returnType((", "), ", ")"], {raw: {value: Object.freeze(["return assert.returnType((", "), ", ")"])}})),
$__680 = Object.freeze(Object.defineProperties(["$traceurRuntime.type.any"], {raw: {value: Object.freeze(["$traceurRuntime.type.any"])}}));
var $__681 = System.get("traceur@0.0.52/src/syntax/trees/ParseTreeType"),
BINDING_ELEMENT = $__681.BINDING_ELEMENT,
REST_PARAMETER = $__681.REST_PARAMETER;
var $__682 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
ImportDeclaration = $__682.ImportDeclaration,
ImportSpecifier = $__682.ImportSpecifier,
ImportSpecifierSet = $__682.ImportSpecifierSet,
Module = $__682.Module,
ModuleSpecifier = $__682.ModuleSpecifier,
Script = $__682.Script,
VariableDeclaration = $__682.VariableDeclaration;
var $__683 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createArgumentList = $__683.createArgumentList,
createIdentifierExpression = $__683.createIdentifierExpression,
createIdentifierToken = $__683.createIdentifierToken,
createStringLiteralToken = $__683.createStringLiteralToken;
var $__684 = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser"),
parseExpression = $__684.parseExpression,
parseStatement = $__684.parseStatement;
var ParameterTransformer = System.get("traceur@0.0.52/src/codegeneration/ParameterTransformer").ParameterTransformer;
var options = System.get("traceur@0.0.52/src/Options").options;
var TypeAssertionTransformer = function TypeAssertionTransformer(identifierGenerator) {
$traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "constructor", [identifierGenerator]);
this.returnTypeStack_ = [];
this.parametersStack_ = [];
this.assertionAdded_ = false;
};
var $TypeAssertionTransformer = TypeAssertionTransformer;
($traceurRuntime.createClass)(TypeAssertionTransformer, {
transformScript: function(tree) {
return this.prependAssertionImport_($traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformScript", [tree]), Script);
},
transformModule: function(tree) {
return this.prependAssertionImport_($traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformModule", [tree]), Module);
},
transformVariableDeclaration: function(tree) {
if (tree.typeAnnotation && tree.initializer) {
var assert = parseExpression($__677, tree.initializer, tree.typeAnnotation);
tree = new VariableDeclaration(tree.location, tree.lvalue, tree.typeAnnotation, assert);
this.assertionAdded_ = true;
}
return $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformVariableDeclaration", [tree]);
},
transformFormalParameterList: function(tree) {
this.parametersStack_.push({
atLeastOneParameterTyped: false,
arguments: []
});
var transformed = $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformFormalParameterList", [tree]);
var params = this.parametersStack_.pop();
if (params.atLeastOneParameterTyped) {
var argumentList = createArgumentList(params.arguments);
var assertStatement = parseStatement($__678, argumentList);
this.parameterStatements.push(assertStatement);
this.assertionAdded_ = true;
}
return transformed;
},
transformFormalParameter: function(tree) {
var transformed = $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformFormalParameter", [tree]);
switch (transformed.parameter.type) {
case BINDING_ELEMENT:
this.transformBindingElementParameter_(transformed.parameter, transformed.typeAnnotation);
break;
case REST_PARAMETER:
break;
}
return transformed;
},
transformGetAccessor: function(tree) {
this.pushReturnType_(tree.typeAnnotation);
tree = $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformGetAccessor", [tree]);
this.popReturnType_();
return tree;
},
transformPropertyMethodAssignment: function(tree) {
this.pushReturnType_(tree.typeAnnotation);
tree = $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformPropertyMethodAssignment", [tree]);
this.popReturnType_();
return tree;
},
transformFunctionDeclaration: function(tree) {
this.pushReturnType_(tree.typeAnnotation);
tree = $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformFunctionDeclaration", [tree]);
this.popReturnType_();
return tree;
},
transformFunctionExpression: function(tree) {
this.pushReturnType_(tree.typeAnnotation);
tree = $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformFunctionExpression", [tree]);
this.popReturnType_();
return tree;
},
transformReturnStatement: function(tree) {
tree = $traceurRuntime.superCall(this, $TypeAssertionTransformer.prototype, "transformReturnStatement", [tree]);
if (this.returnType_ && tree.expression) {
this.assertionAdded_ = true;
return parseStatement($__679, tree.expression, this.returnType_);
}
return tree;
},
transformBindingElementParameter_: function(element, typeAnnotation) {
if (!element.binding.isPattern()) {
if (typeAnnotation) {
this.paramTypes_.atLeastOneParameterTyped = true;
} else {
typeAnnotation = parseExpression($__680);
}
this.paramTypes_.arguments.push(createIdentifierExpression(element.binding.identifierToken), typeAnnotation);
return;
}
},
pushReturnType_: function(typeAnnotation) {
this.returnTypeStack_.push(this.transformAny(typeAnnotation));
},
prependAssertionImport_: function(tree, Ctor) {
if (!this.assertionAdded_ || options.typeAssertionModule === null)
return tree;
var importStatement = new ImportDeclaration(null, new ImportSpecifierSet(null, [new ImportSpecifier(null, createIdentifierToken('assert'), null)]), new ModuleSpecifier(null, createStringLiteralToken(options.typeAssertionModule)));
tree = new Ctor(tree.location, $traceurRuntime.spread([importStatement], tree.scriptItemList), tree.moduleName);
return tree;
},
popReturnType_: function() {
return this.returnTypeStack_.pop();
},
get returnType_() {
return this.returnTypeStack_.length > 0 ? this.returnTypeStack_[this.returnTypeStack_.length - 1] : null;
},
get paramTypes_() {
return this.parametersStack_[this.parametersStack_.length - 1];
}
}, {}, ParameterTransformer);
return {get TypeAssertionTransformer() {
return TypeAssertionTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/TypeToExpressionTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/TypeToExpressionTransformer";
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__689 = System.get("traceur@0.0.52/src/codegeneration/ParseTreeFactory"),
createIdentifierExpression = $__689.createIdentifierExpression,
createMemberExpression = $__689.createMemberExpression;
var TypeToExpressionTransformer = function TypeToExpressionTransformer() {
$traceurRuntime.defaultSuperCall(this, $TypeToExpressionTransformer.prototype, arguments);
};
var $TypeToExpressionTransformer = TypeToExpressionTransformer;
($traceurRuntime.createClass)(TypeToExpressionTransformer, {
transformTypeName: function(tree) {
return createIdentifierExpression(tree.name);
},
transformPredefinedType: function(tree) {
return createMemberExpression('$traceurRuntime', 'type', tree.typeToken);
}
}, {}, ParseTreeTransformer);
return {get TypeToExpressionTransformer() {
return TypeToExpressionTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/TypeTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/TypeTransformer";
var $__691 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
FormalParameter = $__691.FormalParameter,
FunctionDeclaration = $__691.FunctionDeclaration,
FunctionExpression = $__691.FunctionExpression,
GetAccessor = $__691.GetAccessor,
PropertyMethodAssignment = $__691.PropertyMethodAssignment,
VariableDeclaration = $__691.VariableDeclaration;
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var TypeTransformer = function TypeTransformer() {
$traceurRuntime.defaultSuperCall(this, $TypeTransformer.prototype, arguments);
};
var $TypeTransformer = TypeTransformer;
($traceurRuntime.createClass)(TypeTransformer, {
transformVariableDeclaration: function(tree) {
if (tree.typeAnnotation) {
tree = new VariableDeclaration(tree.location, tree.lvalue, null, tree.initializer);
}
return $traceurRuntime.superCall(this, $TypeTransformer.prototype, "transformVariableDeclaration", [tree]);
},
transformFormalParameter: function(tree) {
if (tree.typeAnnotation !== null)
return new FormalParameter(tree.location, tree.parameter, null, []);
return tree;
},
transformFunctionDeclaration: function(tree) {
if (tree.typeAnnotation) {
tree = new FunctionDeclaration(tree.location, tree.name, tree.functionKind, tree.parameterList, null, tree.annotations, tree.body);
}
return $traceurRuntime.superCall(this, $TypeTransformer.prototype, "transformFunctionDeclaration", [tree]);
},
transformFunctionExpression: function(tree) {
if (tree.typeAnnotation) {
tree = new FunctionExpression(tree.location, tree.name, tree.functionKind, tree.parameterList, null, tree.annotations, tree.body);
}
return $traceurRuntime.superCall(this, $TypeTransformer.prototype, "transformFunctionExpression", [tree]);
},
transformPropertyMethodAssignment: function(tree) {
if (tree.typeAnnotation) {
tree = new PropertyMethodAssignment(tree.location, tree.isStatic, tree.functionKind, tree.name, tree.parameterList, null, tree.annotations, tree.body);
}
return $traceurRuntime.superCall(this, $TypeTransformer.prototype, "transformPropertyMethodAssignment", [tree]);
},
transformGetAccessor: function(tree) {
if (tree.typeAnnotation) {
tree = new GetAccessor(tree.location, tree.isStatic, tree.name, null, tree.annotations, tree.body);
}
return $traceurRuntime.superCall(this, $TypeTransformer.prototype, "transformGetAccessor", [tree]);
}
}, {}, ParseTreeTransformer);
return {get TypeTransformer() {
return TypeTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/UniqueIdentifierGenerator", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/UniqueIdentifierGenerator";
var UniqueIdentifierGenerator = function UniqueIdentifierGenerator() {
this.identifierIndex = 0;
};
($traceurRuntime.createClass)(UniqueIdentifierGenerator, {generateUniqueIdentifier: function() {
return ("$__" + this.identifierIndex++);
}}, {});
return {get UniqueIdentifierGenerator() {
return UniqueIdentifierGenerator;
}};
});
System.register("traceur@0.0.52/src/codegeneration/FromOptionsTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/FromOptionsTransformer";
var AmdTransformer = System.get("traceur@0.0.52/src/codegeneration/AmdTransformer").AmdTransformer;
var AnnotationsTransformer = System.get("traceur@0.0.52/src/codegeneration/AnnotationsTransformer").AnnotationsTransformer;
var ArrayComprehensionTransformer = System.get("traceur@0.0.52/src/codegeneration/ArrayComprehensionTransformer").ArrayComprehensionTransformer;
var ArrowFunctionTransformer = System.get("traceur@0.0.52/src/codegeneration/ArrowFunctionTransformer").ArrowFunctionTransformer;
var BlockBindingTransformer = System.get("traceur@0.0.52/src/codegeneration/BlockBindingTransformer").BlockBindingTransformer;
var ClassTransformer = System.get("traceur@0.0.52/src/codegeneration/ClassTransformer").ClassTransformer;
var CommonJsModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/CommonJsModuleTransformer").CommonJsModuleTransformer;
var validateConst = System.get("traceur@0.0.52/src/semantics/ConstChecker").validate;
var DefaultParametersTransformer = System.get("traceur@0.0.52/src/codegeneration/DefaultParametersTransformer").DefaultParametersTransformer;
var DestructuringTransformer = System.get("traceur@0.0.52/src/codegeneration/DestructuringTransformer").DestructuringTransformer;
var ForOfTransformer = System.get("traceur@0.0.52/src/codegeneration/ForOfTransformer").ForOfTransformer;
var validateFreeVariables = System.get("traceur@0.0.52/src/semantics/FreeVariableChecker").validate;
var GeneratorComprehensionTransformer = System.get("traceur@0.0.52/src/codegeneration/GeneratorComprehensionTransformer").GeneratorComprehensionTransformer;
var GeneratorTransformPass = System.get("traceur@0.0.52/src/codegeneration/GeneratorTransformPass").GeneratorTransformPass;
var InlineModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/InlineModuleTransformer").InlineModuleTransformer;
var ModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/ModuleTransformer").ModuleTransformer;
var MultiTransformer = System.get("traceur@0.0.52/src/codegeneration/MultiTransformer").MultiTransformer;
var NumericLiteralTransformer = System.get("traceur@0.0.52/src/codegeneration/NumericLiteralTransformer").NumericLiteralTransformer;
var ObjectLiteralTransformer = System.get("traceur@0.0.52/src/codegeneration/ObjectLiteralTransformer").ObjectLiteralTransformer;
var PropertyNameShorthandTransformer = System.get("traceur@0.0.52/src/codegeneration/PropertyNameShorthandTransformer").PropertyNameShorthandTransformer;
var InstantiateModuleTransformer = System.get("traceur@0.0.52/src/codegeneration/InstantiateModuleTransformer").InstantiateModuleTransformer;
var RestParameterTransformer = System.get("traceur@0.0.52/src/codegeneration/RestParameterTransformer").RestParameterTransformer;
var SpreadTransformer = System.get("traceur@0.0.52/src/codegeneration/SpreadTransformer").SpreadTransformer;
var SymbolTransformer = System.get("traceur@0.0.52/src/codegeneration/SymbolTransformer").SymbolTransformer;
var TemplateLiteralTransformer = System.get("traceur@0.0.52/src/codegeneration/TemplateLiteralTransformer").TemplateLiteralTransformer;
var TypeTransformer = System.get("traceur@0.0.52/src/codegeneration/TypeTransformer").TypeTransformer;
var TypeAssertionTransformer = System.get("traceur@0.0.52/src/codegeneration/TypeAssertionTransformer").TypeAssertionTransformer;
var TypeToExpressionTransformer = System.get("traceur@0.0.52/src/codegeneration/TypeToExpressionTransformer").TypeToExpressionTransformer;
var UniqueIdentifierGenerator = System.get("traceur@0.0.52/src/codegeneration/UniqueIdentifierGenerator").UniqueIdentifierGenerator;
var $__724 = System.get("traceur@0.0.52/src/Options"),
options = $__724.options,
transformOptions = $__724.transformOptions;
var FromOptionsTransformer = function FromOptionsTransformer(reporter) {
var idGenerator = arguments[1] !== (void 0) ? arguments[1] : new UniqueIdentifierGenerator();
var $__725 = this;
$traceurRuntime.superCall(this, $FromOptionsTransformer.prototype, "constructor", [reporter, options.validate]);
var append = (function(transformer) {
$__725.append((function(tree) {
return new transformer(idGenerator, reporter).transformAny(tree);
}));
});
if (transformOptions.blockBinding) {
this.append((function(tree) {
validateConst(tree, reporter);
return tree;
}));
}
if (options.freeVariableChecker) {
this.append((function(tree) {
validateFreeVariables(tree, reporter);
return tree;
}));
}
if (transformOptions.numericLiterals)
append(NumericLiteralTransformer);
if (transformOptions.templateLiterals)
append(TemplateLiteralTransformer);
if (options.types) {
append(TypeToExpressionTransformer);
}
if (transformOptions.annotations)
append(AnnotationsTransformer);
if (options.typeAssertions)
append(TypeAssertionTransformer);
if (transformOptions.propertyNameShorthand)
append(PropertyNameShorthandTransformer);
if (transformOptions.modules) {
switch (transformOptions.modules) {
case 'commonjs':
append(CommonJsModuleTransformer);
break;
case 'amd':
append(AmdTransformer);
break;
case 'inline':
append(InlineModuleTransformer);
break;
case 'instantiate':
append(InstantiateModuleTransformer);
break;
case 'register':
append(ModuleTransformer);
break;
default:
throw new Error('Invalid modules transform option');
}
}
if (transformOptions.arrowFunctions)
append(ArrowFunctionTransformer);
if (transformOptions.classes)
append(ClassTransformer);
if (transformOptions.propertyMethods || transformOptions.computedPropertyNames) {
append(ObjectLiteralTransformer);
}
if (transformOptions.generatorComprehension)
append(GeneratorComprehensionTransformer);
if (transformOptions.arrayComprehension)
append(ArrayComprehensionTransformer);
if (transformOptions.forOf)
append(ForOfTransformer);
if (transformOptions.restParameters)
append(RestParameterTransformer);
if (transformOptions.defaultParameters)
append(DefaultParametersTransformer);
if (transformOptions.destructuring)
append(DestructuringTransformer);
if (transformOptions.types)
append(TypeTransformer);
if (transformOptions.spread)
append(SpreadTransformer);
if (transformOptions.blockBinding)
append(BlockBindingTransformer);
if (transformOptions.generators || transformOptions.asyncFuntions)
append(GeneratorTransformPass);
if (transformOptions.symbols)
append(SymbolTransformer);
};
var $FromOptionsTransformer = FromOptionsTransformer;
($traceurRuntime.createClass)(FromOptionsTransformer, {}, {}, MultiTransformer);
return {get FromOptionsTransformer() {
return FromOptionsTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/PureES6Transformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/PureES6Transformer";
var AnnotationsTransformer = System.get("traceur@0.0.52/src/codegeneration/AnnotationsTransformer").AnnotationsTransformer;
var validateFreeVariables = System.get("traceur@0.0.52/src/semantics/FreeVariableChecker").validate;
var MultiTransformer = System.get("traceur@0.0.52/src/codegeneration/MultiTransformer").MultiTransformer;
var TypeTransformer = System.get("traceur@0.0.52/src/codegeneration/TypeTransformer").TypeTransformer;
var UniqueIdentifierGenerator = System.get("traceur@0.0.52/src/codegeneration/UniqueIdentifierGenerator").UniqueIdentifierGenerator;
var options = System.get("traceur@0.0.52/src/Options").options;
var PureES6Transformer = function PureES6Transformer(reporter) {
var idGenerator = arguments[1] !== (void 0) ? arguments[1] : new UniqueIdentifierGenerator();
var $__733 = this;
$traceurRuntime.superCall(this, $PureES6Transformer.prototype, "constructor", [reporter, options.validate]);
var append = (function(transformer) {
$__733.append((function(tree) {
return new transformer(idGenerator, reporter).transformAny(tree);
}));
});
if (options.freeVariableChecker) {
this.append((function(tree) {
validateFreeVariables(tree, reporter);
return tree;
}));
}
append(AnnotationsTransformer);
append(TypeTransformer);
};
var $PureES6Transformer = PureES6Transformer;
($traceurRuntime.createClass)(PureES6Transformer, {}, {}, MultiTransformer);
return {get PureES6Transformer() {
return PureES6Transformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/AttachModuleNameTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/AttachModuleNameTransformer";
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__736 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
Module = $__736.Module,
Script = $__736.Script;
var AttachModuleNameTransformer = function AttachModuleNameTransformer(moduleName) {
this.moduleName_ = moduleName;
};
($traceurRuntime.createClass)(AttachModuleNameTransformer, {
transformModule: function(tree) {
return new Module(tree.location, tree.scriptItemList, this.moduleName_);
},
transformScript: function(tree) {
return new Script(tree.location, tree.scriptItemList, this.moduleName_);
}
}, {}, ParseTreeTransformer);
return {get AttachModuleNameTransformer() {
return AttachModuleNameTransformer;
}};
});
System.register("traceur@0.0.52/src/util/CollectingErrorReporter", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/CollectingErrorReporter";
var ErrorReporter = System.get("traceur@0.0.52/src/util/ErrorReporter").ErrorReporter;
var CollectingErrorReporter = function CollectingErrorReporter() {
$traceurRuntime.superCall(this, $CollectingErrorReporter.prototype, "constructor", []);
this.errors = [];
};
var $CollectingErrorReporter = CollectingErrorReporter;
($traceurRuntime.createClass)(CollectingErrorReporter, {
reportMessageInternal: function(location, message) {
if (location)
message = (location + ": " + message);
this.errors.push(message);
},
errorsAsString: function() {
return this.errors.join('\n');
},
toException: function() {
return new Error(this.errorsAsString());
}
}, {}, ErrorReporter);
return {get CollectingErrorReporter() {
return CollectingErrorReporter;
}};
});
System.register("traceur@0.0.52/src/Compiler", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/Compiler";
var AttachModuleNameTransformer = System.get("traceur@0.0.52/src/codegeneration/module/AttachModuleNameTransformer").AttachModuleNameTransformer;
var FromOptionsTransformer = System.get("traceur@0.0.52/src/codegeneration/FromOptionsTransformer").FromOptionsTransformer;
var Parser = System.get("traceur@0.0.52/src/syntax/Parser").Parser;
var PureES6Transformer = System.get("traceur@0.0.52/src/codegeneration/PureES6Transformer").PureES6Transformer;
var SourceFile = System.get("traceur@0.0.52/src/syntax/SourceFile").SourceFile;
var SourceMapGenerator = System.get("traceur@0.0.52/src/outputgeneration/SourceMapIntegration").SourceMapGenerator;
var CollectingErrorReporter = System.get("traceur@0.0.52/src/util/CollectingErrorReporter").CollectingErrorReporter;
var $__747 = System.get("traceur@0.0.52/src/Options"),
traceurOptions = $__747.options,
versionLockedOptions = $__747.versionLockedOptions;
var write = System.get("traceur@0.0.52/src/outputgeneration/TreeWriter").write;
function merge() {
for (var srcs = [],
$__751 = 0; $__751 < arguments.length; $__751++)
srcs[$__751] = arguments[$__751];
var dest = Object.create(null);
srcs.forEach((function(src) {
Object.keys(src).forEach((function(key) {
dest[key] = src[key];
}));
var srcModules = src.modules;
if (typeof srcModules !== 'undefined') {
dest.modules = srcModules;
}
}));
return dest;
}
var Compiler = function Compiler() {
var overridingOptions = arguments[0] !== (void 0) ? arguments[0] : {};
this.defaultOptions_ = merge(this.defaultOptions(), overridingOptions);
};
($traceurRuntime.createClass)(Compiler, {
script: function(content) {
var options = arguments[1] !== (void 0) ? arguments[1] : {};
options.modules = false;
return this.compile(content, options);
},
module: function(content) {
var options = arguments[1] !== (void 0) ? arguments[1] : {};
options.modules = 'register';
return this.compile(content, options);
},
compile: function(content) {
var options = arguments[1] !== (void 0) ? arguments[1] : {};
var $__749 = this;
return this.parse({
content: content,
options: options
}).then((function(result) {
return $__749.transform(result);
})).then((function(result) {
return $__749.write(result);
}));
},
stringToString: function(content) {
var options = arguments[1] !== (void 0) ? arguments[1] : {};
var output = this.stringToTree({
content: content,
options: options
});
if (output.errors.length)
return output;
output = this.treeToTree(output);
if (output.errors.length)
return output;
return this.treeToString(output);
},
stringToTree: function($__752) {
var $__754;
var $__753 = $traceurRuntime.assertObject($__752),
content = $__753.content,
options = ($__754 = $__753.options) === void 0 ? {} : $__754;
var mergedOptions = merge(this.defaultOptions_, options);
options = traceurOptions.setFromObject(mergedOptions);
var errorReporter = new CollectingErrorReporter();
var sourceFile = new SourceFile(mergedOptions.filename, content);
var parser = new Parser(sourceFile, errorReporter);
var tree = mergedOptions.modules ? parser.parseModule() : parser.parseScript();
return {
tree: tree,
options: mergedOptions,
errors: errorReporter.errors
};
},
parse: function(input) {
return this.promise(this.stringToTree, input);
},
treeToTree: function($__752) {
var $__754 = $traceurRuntime.assertObject($__752),
tree = $__754.tree,
options = $__754.options;
var transformer;
if (options.moduleName) {
var moduleName = options.moduleName;
if (typeof moduleName !== 'string')
moduleName = this.resolveModuleName(options.filename);
if (moduleName) {
transformer = new AttachModuleNameTransformer(moduleName);
tree = transformer.transformAny(tree);
}
}
var errorReporter = new CollectingErrorReporter();
if (options.outputLanguage.toLowerCase() === 'es6') {
transformer = new PureES6Transformer(errorReporter);
} else {
transformer = new FromOptionsTransformer(errorReporter);
}
var transformedTree = transformer.transform(tree);
if (errorReporter.hadError()) {
return {
js: null,
errors: errorReporter.errors
};
} else {
return {
tree: transformedTree,
options: options,
errors: errorReporter.errors
};
}
},
transform: function(input) {
return this.promise(this.treeToTree, input);
},
treeToString: function($__752) {
var $__754 = $traceurRuntime.assertObject($__752),
tree = $__754.tree,
options = $__754.options,
errors = $__754.errors;
var treeWriterOptions = {};
if (options.sourceMaps) {
treeWriterOptions.sourceMapGenerator = new SourceMapGenerator({
file: options.filename,
sourceRoot: this.sourceRootForFilename(options.filename)
});
}
return {
js: write(tree, treeWriterOptions),
errors: errors,
generatedSourceMap: treeWriterOptions.generatedSourceMap || null
};
},
write: function(input) {
return this.promise(this.treeToString, input);
},
resolveModuleName: function(filename) {
return filename;
},
sourceRootForFilename: function(filename) {
return filename;
},
defaultOptions: function() {
return versionLockedOptions;
},
promise: function(method, input) {
var $__749 = this;
return new Promise((function(resolve, reject) {
var output = method.call($__749, input);
if (output.errors.length)
reject(new Error(output.errors.join('\n')));
else
resolve(output);
}));
}
}, {
amdOptions: function() {
var options = arguments[0] !== (void 0) ? arguments[0] : {};
var amdOptions = {
modules: 'amd',
filename: undefined,
sourceMap: false,
moduleName: true
};
return merge(amdOptions, options);
},
commonJSOptions: function() {
var options = arguments[0] !== (void 0) ? arguments[0] : {};
var commonjsOptions = {
modules: 'commonjs',
filename: '<unknown file>',
sourceMap: false,
moduleName: false
};
return merge(commonjsOptions, options);
}
});
return {get Compiler() {
return Compiler;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/ValidationVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/ValidationVisitor";
var ModuleVisitor = System.get("traceur@0.0.52/src/codegeneration/module/ModuleVisitor").ModuleVisitor;
var ValidationVisitor = function ValidationVisitor() {
$traceurRuntime.defaultSuperCall(this, $ValidationVisitor.prototype, arguments);
};
var $ValidationVisitor = ValidationVisitor;
($traceurRuntime.createClass)(ValidationVisitor, {
checkExport_: function(tree, name) {
var description = this.validatingModuleDescription_;
if (description && !description.getExport(name)) {
var moduleName = description.normalizedName;
this.reportError(tree, ("'" + name + "' is not exported by '" + moduleName + "'"));
}
},
checkImport_: function(tree, name) {
var existingImport = this.moduleSymbol.getImport(name);
if (existingImport) {
this.reportError(tree, ("'" + name + "' was previously imported at " + existingImport.location.start));
} else {
this.moduleSymbol.addImport(name, tree);
}
},
visitAndValidate_: function(moduleDescription, tree) {
var validatingModuleDescription = this.validatingModuleDescription_;
this.validatingModuleDescription_ = moduleDescription;
this.visitAny(tree);
this.validatingModuleDescription_ = validatingModuleDescription;
},
visitNamedExport: function(tree) {
if (tree.moduleSpecifier) {
var name = tree.moduleSpecifier.token.processedValue;
var moduleDescription = this.getModuleDescriptionForModuleSpecifier(name);
this.visitAndValidate_(moduleDescription, tree.specifierSet);
}
},
visitExportSpecifier: function(tree) {
this.checkExport_(tree, tree.lhs.value);
},
visitImportDeclaration: function(tree) {
var name = tree.moduleSpecifier.token.processedValue;
var moduleDescription = this.getModuleDescriptionForModuleSpecifier(name);
this.visitAndValidate_(moduleDescription, tree.importClause);
},
visitImportSpecifier: function(tree) {
var importName = tree.rhs ? tree.rhs.value : tree.lhs.value;
this.checkImport_(tree, importName);
this.checkExport_(tree, tree.lhs.value);
},
visitImportedBinding: function(tree) {
var importName = tree.binding.identifierToken.value;
this.checkImport_(tree, importName);
this.checkExport_(tree, 'default');
}
}, {}, ModuleVisitor);
return {get ValidationVisitor() {
return ValidationVisitor;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/ExportListBuilder", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/ExportListBuilder";
var ExportVisitor = System.get("traceur@0.0.52/src/codegeneration/module/ExportVisitor").ExportVisitor;
var ValidationVisitor = System.get("traceur@0.0.52/src/codegeneration/module/ValidationVisitor").ValidationVisitor;
var transformOptions = System.get("traceur@0.0.52/src/Options").transformOptions;
function buildExportList(deps, loader, reporter) {
if (!transformOptions.modules)
return;
function doVisit(ctor) {
for (var i = 0; i < deps.length; i++) {
var visitor = new ctor(reporter, loader, deps[i].moduleSymbol);
visitor.visitAny(deps[i].tree);
}
}
function reverseVisit(ctor) {
for (var i = deps.length - 1; i >= 0; i--) {
var visitor = new ctor(reporter, loader, deps[i].moduleSymbol);
visitor.visitAny(deps[i].tree);
}
}
reverseVisit(ExportVisitor);
doVisit(ValidationVisitor);
}
return {get buildExportList() {
return buildExportList;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/ModuleSpecifierVisitor", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/ModuleSpecifierVisitor";
var ParseTreeVisitor = System.get("traceur@0.0.52/src/syntax/ParseTreeVisitor").ParseTreeVisitor;
var options = System.get("traceur@0.0.52/src/Options").options;
var ModuleSpecifierVisitor = function ModuleSpecifierVisitor() {
$traceurRuntime.superCall(this, $ModuleSpecifierVisitor.prototype, "constructor", []);
this.moduleSpecifiers_ = Object.create(null);
};
var $ModuleSpecifierVisitor = ModuleSpecifierVisitor;
($traceurRuntime.createClass)(ModuleSpecifierVisitor, {
get moduleSpecifiers() {
return Object.keys(this.moduleSpecifiers_);
},
visitModuleSpecifier: function(tree) {
this.moduleSpecifiers_[tree.token.processedValue] = true;
},
visitVariableDeclaration: function(tree) {
this.addTypeAssertionDependency_(tree.typeAnnotation);
return $traceurRuntime.superCall(this, $ModuleSpecifierVisitor.prototype, "visitVariableDeclaration", [tree]);
},
visitFormalParameter: function(tree) {
this.addTypeAssertionDependency_(tree.typeAnnotation);
return $traceurRuntime.superCall(this, $ModuleSpecifierVisitor.prototype, "visitFormalParameter", [tree]);
},
visitGetAccessor: function(tree) {
this.addTypeAssertionDependency_(tree.typeAnnotation);
return $traceurRuntime.superCall(this, $ModuleSpecifierVisitor.prototype, "visitGetAccessor", [tree]);
},
visitPropertyMethodAssignment: function(tree) {
this.addTypeAssertionDependency_(tree.typeAnnotation);
return $traceurRuntime.superCall(this, $ModuleSpecifierVisitor.prototype, "visitPropertyMethodAssignment", [tree]);
},
visitFunctionDeclaration: function(tree) {
this.addTypeAssertionDependency_(tree.typeAnnotation);
return $traceurRuntime.superCall(this, $ModuleSpecifierVisitor.prototype, "visitFunctionDeclaration", [tree]);
},
visitFunctionExpression: function(tree) {
this.addTypeAssertionDependency_(tree.typeAnnotation);
return $traceurRuntime.superCall(this, $ModuleSpecifierVisitor.prototype, "visitFunctionExpression", [tree]);
},
addTypeAssertionDependency_: function(typeAnnotation) {
if (typeAnnotation !== null && options.typeAssertionModule !== null)
this.moduleSpecifiers_[options.typeAssertionModule] = true;
}
}, {}, ParseTreeVisitor);
return {get ModuleSpecifierVisitor() {
return ModuleSpecifierVisitor;
}};
});
System.register("traceur@0.0.52/src/runtime/system-map", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/system-map";
function prefixMatchLength(name, prefix) {
var prefixParts = prefix.split('/');
var nameParts = name.split('/');
if (prefixParts.length > nameParts.length)
return 0;
for (var i = 0; i < prefixParts.length; i++) {
if (nameParts[i] != prefixParts[i])
return 0;
}
return prefixParts.length;
}
function applyMap(map, name, parentName) {
var curMatch,
curMatchLength = 0;
var curParent,
curParentMatchLength = 0;
if (parentName) {
var mappedName;
Object.getOwnPropertyNames(map).some(function(p) {
var curMap = map[p];
if (curMap && typeof curMap === 'object') {
if (prefixMatchLength(parentName, p) <= curParentMatchLength)
return;
Object.getOwnPropertyNames(curMap).forEach(function(q) {
if (prefixMatchLength(name, q) > curMatchLength) {
curMatch = q;
curMatchLength = q.split('/').length;
curParent = p;
curParentMatchLength = p.split('/').length;
}
});
}
if (curMatch) {
var subPath = name.split('/').splice(curMatchLength).join('/');
mappedName = map[curParent][curMatch] + (subPath ? '/' + subPath : '');
return mappedName;
}
});
}
if (mappedName)
return mappedName;
Object.getOwnPropertyNames(map).forEach(function(p) {
var curMap = map[p];
if (curMap && typeof curMap === 'string') {
if (prefixMatchLength(name, p) > curMatchLength) {
curMatch = p;
curMatchLength = p.split('/').length;
}
}
});
if (!curMatch)
return name;
var subPath = name.split('/').splice(curMatchLength).join('/');
return map[curMatch] + (subPath ? '/' + subPath : '');
}
var systemjs = {applyMap: applyMap};
return {get systemjs() {
return systemjs;
}};
});
System.register("traceur@0.0.52/src/util/url", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/util/url";
var canonicalizeUrl = $traceurRuntime.canonicalizeUrl;
var isAbsolute = $traceurRuntime.isAbsolute;
var removeDotSegments = $traceurRuntime.removeDotSegments;
var resolveUrl = $traceurRuntime.resolveUrl;
return {
get canonicalizeUrl() {
return canonicalizeUrl;
},
get isAbsolute() {
return isAbsolute;
},
get removeDotSegments() {
return removeDotSegments;
},
get resolveUrl() {
return resolveUrl;
}
};
});
System.register("traceur@0.0.52/src/runtime/webLoader", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/webLoader";
var webLoader = {load: function(url, callback, errback) {
var xhr = new XMLHttpRequest();
xhr.onload = (function() {
if (xhr.status == 200 || xhr.status == 0) {
callback(xhr.responseText);
} else {
var err;
if (xhr.status === 404)
err = 'File not found \'' + url + '\'';
else
err = xhr.status + xhr.statusText;
errback(err);
}
xhr = null;
});
xhr.onerror = (function(err) {
errback(err);
});
xhr.open('GET', url, true);
xhr.send();
return (function() {
xhr && xhr.abort();
});
}};
return {get webLoader() {
return webLoader;
}};
});
System.register("traceur@0.0.52/src/runtime/LoaderHooks", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/LoaderHooks";
var AttachModuleNameTransformer = System.get("traceur@0.0.52/src/codegeneration/module/AttachModuleNameTransformer").AttachModuleNameTransformer;
var FromOptionsTransformer = System.get("traceur@0.0.52/src/codegeneration/FromOptionsTransformer").FromOptionsTransformer;
var buildExportList = System.get("traceur@0.0.52/src/codegeneration/module/ExportListBuilder").buildExportList;
var CollectingErrorReporter = System.get("traceur@0.0.52/src/util/CollectingErrorReporter").CollectingErrorReporter;
var ModuleSpecifierVisitor = System.get("traceur@0.0.52/src/codegeneration/module/ModuleSpecifierVisitor").ModuleSpecifierVisitor;
var ModuleSymbol = System.get("traceur@0.0.52/src/codegeneration/module/ModuleSymbol").ModuleSymbol;
var Parser = System.get("traceur@0.0.52/src/syntax/Parser").Parser;
var options = System.get("traceur@0.0.52/src/Options").options;
var SourceFile = System.get("traceur@0.0.52/src/syntax/SourceFile").SourceFile;
var systemjs = System.get("traceur@0.0.52/src/runtime/system-map").systemjs;
var UniqueIdentifierGenerator = System.get("traceur@0.0.52/src/codegeneration/UniqueIdentifierGenerator").UniqueIdentifierGenerator;
var $__774 = System.get("traceur@0.0.52/src/util/url"),
isAbsolute = $__774.isAbsolute,
resolveUrl = $__774.resolveUrl;
var webLoader = System.get("traceur@0.0.52/src/runtime/webLoader").webLoader;
var assert = System.get("traceur@0.0.52/src/util/assert").assert;
var NOT_STARTED = 0;
var LOADING = 1;
var LOADED = 2;
var PARSED = 3;
var TRANSFORMING = 4;
var TRANSFORMED = 5;
var COMPLETE = 6;
var ERROR = 7;
var identifierGenerator = new UniqueIdentifierGenerator();
var LoaderHooks = function LoaderHooks(reporter, baseURL) {
var fileLoader = arguments[2] !== (void 0) ? arguments[2] : webLoader;
var moduleStore = arguments[3] !== (void 0) ? arguments[3] : $traceurRuntime.ModuleStore;
this.baseURL_ = baseURL;
this.moduleStore_ = moduleStore;
this.fileLoader = fileLoader;
};
($traceurRuntime.createClass)(LoaderHooks, {
get: function(normalizedName) {
return this.moduleStore_.get(normalizedName);
},
set: function(normalizedName, module) {
this.moduleStore_.set(normalizedName, module);
},
normalize: function(name, referrerName, referrerAddress) {
var normalizedName = this.moduleStore_.normalize(name, referrerName, referrerAddress);
if (System.map)
return systemjs.applyMap(System.map, normalizedName, referrerName);
else
return normalizedName;
},
get baseURL() {
return this.baseURL_;
},
set baseURL(value) {
this.baseURL_ = String(value);
},
getModuleSpecifiers: function(codeUnit) {
this.parse(codeUnit);
codeUnit.state = PARSED;
var moduleSpecifierVisitor = new ModuleSpecifierVisitor();
moduleSpecifierVisitor.visit(codeUnit.metadata.tree);
return moduleSpecifierVisitor.moduleSpecifiers;
},
parse: function(codeUnit) {
assert(!codeUnit.metadata.tree);
var reporter = new CollectingErrorReporter();
var normalizedName = codeUnit.normalizedName;
var program = codeUnit.source;
var url = codeUnit.url || normalizedName;
var file = new SourceFile(url, program);
this.checkForErrors((function(reporter) {
var parser = new Parser(file, reporter);
if (codeUnit.type == 'module')
codeUnit.metadata.tree = parser.parseModule();
else
codeUnit.metadata.tree = parser.parseScript();
}));
codeUnit.metadata.moduleSymbol = new ModuleSymbol(codeUnit.metadata.tree, normalizedName);
},
transform: function(codeUnit) {
var transformer = new AttachModuleNameTransformer(codeUnit.normalizedName);
var transformedTree = transformer.transformAny(codeUnit.metadata.tree);
return this.checkForErrors((function(reporter) {
transformer = new FromOptionsTransformer(reporter, identifierGenerator);
return transformer.transform(transformedTree);
}));
},
fetch: function(load) {
var $__777 = this;
return new Promise((function(resolve, reject) {
if (!load)
reject(new TypeError('fetch requires argument object'));
else if (!load.address || typeof load.address !== 'string')
reject(new TypeError('fetch({address}) missing required string.'));
else
$__777.fileLoader.load(load.address, resolve, reject);
}));
},
translate: function(load) {
return new Promise((function(resolve, reject) {
resolve(load.source);
}));
},
instantiate: function($__779) {
var $__780 = $traceurRuntime.assertObject($__779),
name = $__780.name,
metadata = $__780.metadata,
address = $__780.address,
source = $__780.source,
sourceMap = $__780.sourceMap;
return new Promise((function(resolve, reject) {
resolve(undefined);
}));
},
locate: function(load) {
load.url = this.locate_(load);
return load.url;
},
locate_: function(load) {
var normalizedModuleName = load.normalizedName;
var asJS;
if (load.type === 'script') {
asJS = normalizedModuleName;
} else {
asJS = normalizedModuleName + '.js';
}
if (options.referrer) {
if (asJS.indexOf(options.referrer) === 0) {
asJS = asJS.slice(options.referrer.length);
load.metadata.locateMap = {
pattern: options.referrer,
replacement: ''
};
}
}
if (isAbsolute(asJS))
return asJS;
var baseURL = load.metadata && load.metadata.baseURL;
baseURL = baseURL || this.baseURL;
if (baseURL) {
load.metadata.baseURL = baseURL;
return resolveUrl(baseURL, asJS);
}
return asJS;
},
nameTrace: function(load) {
var trace = '';
if (load.metadata.locateMap) {
trace += this.locateMapTrace(load);
}
var base = load.metadata.baseURL || this.baseURL;
if (base) {
trace += this.baseURLTrace(base);
} else {
trace += 'No baseURL\n';
}
return trace;
},
locateMapTrace: function(load) {
var map = load.metadata.locateMap;
return ("LoaderHooks.locate found \'" + map.pattern + "\' -> \'" + map.replacement + "\'\n");
},
baseURLTrace: function(base) {
return 'LoaderHooks.locate resolved against base \'' + base + '\'\n';
},
evaluateCodeUnit: function(codeUnit) {
var result = ('global', eval)(codeUnit.metadata.transcoded);
codeUnit.metadata.transformedTree = null;
return result;
},
analyzeDependencies: function(dependencies, loader) {
var deps = [];
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
assert(codeUnit.state >= PARSED);
if (codeUnit.state == PARSED) {
deps.push(codeUnit.metadata);
}
}
this.checkForErrors((function(reporter) {
return buildExportList(deps, loader, reporter);
}));
},
bundledModule: function(name) {
return this.moduleStore_.bundleStore[name];
},
checkForErrors: function(fncOfReporter) {
var reporter = new CollectingErrorReporter();
var result = fncOfReporter(reporter);
if (reporter.hadError())
throw reporter.toException();
return result;
}
}, {});
return {get LoaderHooks() {
return LoaderHooks;
}};
});
System.register("traceur@0.0.52/src/runtime/InterceptOutputLoaderHooks", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/InterceptOutputLoaderHooks";
var LoaderHooks = System.get("traceur@0.0.52/src/runtime/LoaderHooks").LoaderHooks;
var InterceptOutputLoaderHooks = function InterceptOutputLoaderHooks() {
for (var args = [],
$__783 = 0; $__783 < arguments.length; $__783++)
args[$__783] = arguments[$__783];
$traceurRuntime.superCall(this, $InterceptOutputLoaderHooks.prototype, "constructor", $traceurRuntime.spread(args));
this.sourceMap = null;
this.transcoded = null;
this.onTranscoded = (function() {});
};
var $InterceptOutputLoaderHooks = InterceptOutputLoaderHooks;
($traceurRuntime.createClass)(InterceptOutputLoaderHooks, {instantiate: function($__784) {
var $__785 = $traceurRuntime.assertObject($__784),
metadata = $__785.metadata,
url = $__785.url;
this.sourceMap = metadata.sourceMap;
this.transcoded = metadata.transcoded;
this.onTranscoded(metadata, url);
return undefined;
}}, {}, LoaderHooks);
return {get InterceptOutputLoaderHooks() {
return InterceptOutputLoaderHooks;
}};
});
System.register("traceur@0.0.52/src/runtime/InternalLoader", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/InternalLoader";
var LoaderHooks = System.get("traceur@0.0.52/src/runtime/LoaderHooks").LoaderHooks;
var Map = System.get("traceur@0.0.52/src/runtime/polyfills/Map").Map;
var $__788 = System.get("traceur@0.0.52/src/util/url"),
isAbsolute = $__788.isAbsolute,
resolveUrl = $__788.resolveUrl;
var options = System.get("traceur@0.0.52/src/Options").options;
var toSource = System.get("traceur@0.0.52/src/outputgeneration/toSource").toSource;
var NOT_STARTED = 0;
var LOADING = 1;
var LOADED = 2;
var PARSED = 3;
var TRANSFORMING = 4;
var TRANSFORMED = 5;
var COMPLETE = 6;
var ERROR = 7;
function mapToValues(map) {
var array = [];
map.forEach((function(v) {
array.push(v);
}));
return array;
}
var CodeUnit = function CodeUnit(loaderHooks, normalizedName, type, state, name, referrerName, address) {
var $__791 = this;
this.promise = new Promise((function(res, rej) {
$__791.loaderHooks = loaderHooks;
$__791.normalizedName = normalizedName;
$__791.type = type;
$__791.name_ = name;
$__791.referrerName_ = referrerName;
$__791.address = address;
$__791.url = InternalLoader.uniqueName(normalizedName, address);
$__791.state_ = state || NOT_STARTED;
$__791.error = null;
$__791.result = null;
$__791.data_ = {};
$__791.dependencies = [];
$__791.resolve = res;
$__791.reject = rej;
}));
};
($traceurRuntime.createClass)(CodeUnit, {
get state() {
return this.state_;
},
set state(state) {
if (state < this.state_) {
throw new Error('Invalid state change');
}
this.state_ = state;
},
get metadata() {
return this.data_;
},
nameTrace: function() {
var trace = this.specifiedAs();
if (isAbsolute(this.name_)) {
return trace + 'An absolute name.\n';
}
if (this.referrerName_) {
return trace + this.importedBy() + this.normalizesTo();
}
return trace + this.normalizesTo();
},
specifiedAs: function() {
return ("Specified as " + this.name_ + ".\n");
},
importedBy: function() {
return ("Imported by " + this.referrerName_ + ".\n");
},
normalizesTo: function() {
return 'Normalizes to ' + this.normalizedName + '\n';
},
transform: function() {
return this.loaderHooks.transform(this);
},
instantiate: function(load) {
return this.loaderHooks.instantiate(this);
}
}, {});
var PreCompiledCodeUnit = function PreCompiledCodeUnit(loaderHooks, normalizedName, name, referrerName, address, module) {
$traceurRuntime.superCall(this, $PreCompiledCodeUnit.prototype, "constructor", [loaderHooks, normalizedName, 'module', COMPLETE, name, referrerName, address]);
this.result = module;
this.resolve(this.result);
};
var $PreCompiledCodeUnit = PreCompiledCodeUnit;
($traceurRuntime.createClass)(PreCompiledCodeUnit, {}, {}, CodeUnit);
var BundledCodeUnit = function BundledCodeUnit(loaderHooks, normalizedName, name, referrerName, address, deps, execute) {
$traceurRuntime.superCall(this, $BundledCodeUnit.prototype, "constructor", [loaderHooks, normalizedName, 'module', TRANSFORMED, name, referrerName, address]);
this.deps = deps;
this.execute = execute;
};
var $BundledCodeUnit = BundledCodeUnit;
($traceurRuntime.createClass)(BundledCodeUnit, {
getModuleSpecifiers: function() {
return this.deps;
},
evaluate: function() {
var $__791 = this;
var normalizedNames = this.deps.map((function(name) {
return $__791.loaderHooks.normalize(name);
}));
var module = this.execute.apply(Reflect.global, normalizedNames);
System.set(this.normalizedName, module);
return module;
}
}, {}, CodeUnit);
var HookedCodeUnit = function HookedCodeUnit() {
$traceurRuntime.defaultSuperCall(this, $HookedCodeUnit.prototype, arguments);
};
var $HookedCodeUnit = HookedCodeUnit;
($traceurRuntime.createClass)(HookedCodeUnit, {
getModuleSpecifiers: function() {
return this.loaderHooks.getModuleSpecifiers(this);
},
evaluate: function() {
return this.loaderHooks.evaluateCodeUnit(this);
}
}, {}, CodeUnit);
var LoadCodeUnit = function LoadCodeUnit(loaderHooks, normalizedName, name, referrerName, address) {
$traceurRuntime.superCall(this, $LoadCodeUnit.prototype, "constructor", [loaderHooks, normalizedName, 'module', NOT_STARTED, name, referrerName, address]);
};
var $LoadCodeUnit = LoadCodeUnit;
($traceurRuntime.createClass)(LoadCodeUnit, {}, {}, HookedCodeUnit);
var EvalCodeUnit = function EvalCodeUnit(loaderHooks, code) {
var type = arguments[2] !== (void 0) ? arguments[2] : 'script';
var normalizedName = arguments[3];
var referrerName = arguments[4];
var address = arguments[5];
$traceurRuntime.superCall(this, $EvalCodeUnit.prototype, "constructor", [loaderHooks, normalizedName, type, LOADED, null, referrerName, address]);
this.source = code;
};
var $EvalCodeUnit = EvalCodeUnit;
($traceurRuntime.createClass)(EvalCodeUnit, {}, {}, HookedCodeUnit);
var uniqueNameCount = 0;
var InternalLoader = function InternalLoader(loaderHooks) {
this.loaderHooks = loaderHooks;
this.cache = new Map();
this.urlToKey = Object.create(null);
this.sync_ = false;
};
($traceurRuntime.createClass)(InternalLoader, {
load: function(name) {
var referrerName = arguments[1] !== (void 0) ? arguments[1] : this.loaderHooks.baseURL;
var address = arguments[2];
var type = arguments[3] !== (void 0) ? arguments[3] : 'script';
var codeUnit = this.load_(name, referrerName, address, type);
return codeUnit.promise.then((function() {
return codeUnit;
}));
},
load_: function(name, referrerName, address, type) {
var $__791 = this;
var codeUnit = this.getCodeUnit_(name, referrerName, address, type);
if (codeUnit.state === ERROR) {
return codeUnit;
}
if (codeUnit.state === TRANSFORMED) {
this.handleCodeUnitLoaded(codeUnit);
} else {
if (codeUnit.state !== NOT_STARTED)
return codeUnit;
codeUnit.state = LOADING;
codeUnit.address = this.loaderHooks.locate(codeUnit);
this.loaderHooks.fetch(codeUnit).then((function(text) {
codeUnit.source = text;
return codeUnit;
})).then(this.loaderHooks.translate.bind(this.loaderHooks)).then((function(source) {
codeUnit.source = source;
codeUnit.state = LOADED;
$__791.handleCodeUnitLoaded(codeUnit);
return codeUnit;
})).catch((function(err) {
try {
codeUnit.state = ERROR;
codeUnit.error = err;
$__791.handleCodeUnitLoadError(codeUnit);
} catch (ex) {
console.error('Internal Error ' + (ex.stack || ex));
}
}));
}
return codeUnit;
},
module: function(code, referrerName, address) {
var codeUnit = new EvalCodeUnit(this.loaderHooks, code, 'module', null, referrerName, address);
this.cache.set({}, codeUnit);
this.handleCodeUnitLoaded(codeUnit);
return codeUnit.promise;
},
define: function(normalizedName, code, address) {
var codeUnit = new EvalCodeUnit(this.loaderHooks, code, 'module', normalizedName, null, address);
var key = this.getKey(normalizedName, 'module');
this.cache.set(key, codeUnit);
this.handleCodeUnitLoaded(codeUnit);
return codeUnit.promise;
},
script: function(code, name, referrerName, address) {
var normalizedName = System.normalize(name || '', referrerName, address);
var codeUnit = new EvalCodeUnit(this.loaderHooks, code, 'script', normalizedName, referrerName, address);
var key = {};
if (name)
key = this.getKey(normalizedName, 'script');
this.cache.set(key, codeUnit);
this.handleCodeUnitLoaded(codeUnit);
return codeUnit.promise;
},
sourceMapInfo: function(normalizedName, type) {
var key = this.getKey(normalizedName, type);
var codeUnit = this.cache.get(key);
return {
sourceMap: codeUnit && codeUnit.metadata && codeUnit.metadata.sourceMap,
url: codeUnit && codeUnit.url
};
},
getKey: function(url, type) {
var combined = type + ':' + url;
if (combined in this.urlToKey) {
return this.urlToKey[combined];
}
return this.urlToKey[combined] = {};
},
getCodeUnit_: function(name, referrerName, address, type) {
var normalizedName = System.normalize(name, referrerName, address);
var key = this.getKey(normalizedName, type);
var cacheObject = this.cache.get(key);
if (!cacheObject) {
var module = this.loaderHooks.get(normalizedName);
if (module) {
cacheObject = new PreCompiledCodeUnit(this.loaderHooks, normalizedName, name, referrerName, address, module);
cacheObject.type = 'module';
} else {
var bundledModule = this.loaderHooks.bundledModule(name);
if (bundledModule) {
cacheObject = new BundledCodeUnit(this.loaderHooks, normalizedName, name, referrerName, address, bundledModule.deps, bundledModule.execute);
} else {
cacheObject = new LoadCodeUnit(this.loaderHooks, normalizedName, name, referrerName, address);
cacheObject.type = type;
}
}
this.cache.set(key, cacheObject);
}
return cacheObject;
},
areAll: function(state) {
return mapToValues(this.cache).every((function(codeUnit) {
return codeUnit.state >= state;
}));
},
getCodeUnitForModuleSpecifier: function(name, referrerName) {
return this.getCodeUnit_(name, referrerName, null, 'module');
},
handleCodeUnitLoaded: function(codeUnit) {
var $__791 = this;
var referrerName = codeUnit.normalizedName;
try {
var moduleSpecifiers = codeUnit.getModuleSpecifiers();
if (!moduleSpecifiers) {
this.abortAll(("No module specifiers in " + referrerName));
return;
}
codeUnit.dependencies = moduleSpecifiers.sort().map((function(name) {
return $__791.getCodeUnit_(name, referrerName, null, 'module');
}));
} catch (error) {
this.rejectOneAndAll(codeUnit, error);
return;
}
codeUnit.dependencies.forEach((function(dependency) {
$__791.load(dependency.normalizedName, null, null, 'module');
}));
if (this.areAll(PARSED)) {
try {
this.analyze();
this.transform();
this.evaluate();
} catch (error) {
this.rejectOneAndAll(codeUnit, error);
}
}
},
rejectOneAndAll: function(codeUnit, error) {
codeUnit.state.ERROR;
codeUnit.error = error;
codeUnit.reject(error);
this.abortAll(error);
},
handleCodeUnitLoadError: function(codeUnit) {
var message = codeUnit.error ? String(codeUnit.error) + '\n' : ("Failed to load '" + codeUnit.address + "'.\n");
message += codeUnit.nameTrace() + this.loaderHooks.nameTrace(codeUnit);
this.rejectOneAndAll(codeUnit, new Error(message));
},
abortAll: function(errorMessage) {
this.cache.forEach((function(codeUnit) {
if (codeUnit.state !== ERROR)
codeUnit.reject(errorMessage);
}));
},
analyze: function() {
this.loaderHooks.analyzeDependencies(mapToValues(this.cache), this);
},
transform: function() {
this.transformDependencies_(mapToValues(this.cache));
},
transformDependencies_: function(dependencies, dependentName) {
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
if (codeUnit.state >= TRANSFORMED) {
continue;
}
if (codeUnit.state === TRANSFORMING) {
var cir = codeUnit.normalizedName;
var cle = dependentName;
this.rejectOneAndAll(codeUnit, new Error(("Unsupported circular dependency between " + cir + " and " + cle)));
return;
}
codeUnit.state = TRANSFORMING;
try {
this.transformCodeUnit_(codeUnit);
} catch (error) {
this.rejectOneAndAll(codeUnit, error);
return;
}
}
},
transformCodeUnit_: function(codeUnit) {
var $__793;
this.transformDependencies_(codeUnit.dependencies, codeUnit.normalizedName);
if (codeUnit.state === ERROR)
return;
var metadata = codeUnit.metadata;
metadata.transformedTree = codeUnit.transform();
codeUnit.state = TRANSFORMED;
var filename = codeUnit.address || codeUnit.normalizedName;
($__793 = $traceurRuntime.assertObject(toSource(metadata.transformedTree, options, filename)), metadata.transcoded = $__793[0], metadata.sourceMap = $__793[1], $__793);
if (codeUnit.address && metadata.transcoded)
metadata.transcoded += '//# sourceURL=' + codeUnit.address;
codeUnit.instantiate();
},
orderDependencies: function() {
var visited = new Map();
var ordered = [];
function orderCodeUnits(codeUnit) {
if (visited.has(codeUnit)) {
return;
}
visited.set(codeUnit, true);
codeUnit.dependencies.forEach(orderCodeUnits);
ordered.push(codeUnit);
}
this.cache.forEach(orderCodeUnits);
return ordered;
},
evaluate: function() {
var dependencies = this.orderDependencies();
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
if (codeUnit.state >= COMPLETE) {
continue;
}
var result;
try {
result = codeUnit.evaluate();
} catch (ex) {
this.rejectOneAndAll(codeUnit, ex);
return;
}
codeUnit.result = result;
codeUnit.source = null;
}
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
if (codeUnit.state >= COMPLETE) {
continue;
}
codeUnit.state = COMPLETE;
codeUnit.resolve(codeUnit.result);
}
}
}, {uniqueName: function(normalizedName, referrerAddress) {
var importerAddress = referrerAddress || System.baseURL;
if (!importerAddress)
throw new Error('The System.baseURL is an empty string');
var path = normalizedName || String(uniqueNameCount++);
return resolveUrl(importerAddress, path);
}});
var SystemLoaderHooks = LoaderHooks;
var internals = {
CodeUnit: CodeUnit,
EvalCodeUnit: EvalCodeUnit,
LoadCodeUnit: LoadCodeUnit,
LoaderHooks: LoaderHooks
};
return {
get InternalLoader() {
return InternalLoader;
},
get internals() {
return internals;
}
};
});
System.register("traceur@0.0.52/src/runtime/Loader", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/Loader";
var InternalLoader = System.get("traceur@0.0.52/src/runtime/InternalLoader").InternalLoader;
var Loader = function Loader(loaderHooks) {
this.internalLoader_ = new InternalLoader(loaderHooks);
this.loaderHooks_ = loaderHooks;
};
($traceurRuntime.createClass)(Loader, {
import: function(name) {
var $__797 = $traceurRuntime.assertObject(arguments[1] !== (void 0) ? arguments[1] : {}),
referrerName = $__797.referrerName,
address = $__797.address;
var $__795 = this;
return this.internalLoader_.load(name, referrerName, address, 'module').then((function(codeUnit) {
return $__795.get(codeUnit.normalizedName);
}));
},
module: function(source) {
var $__797 = $traceurRuntime.assertObject(arguments[1] !== (void 0) ? arguments[1] : {}),
referrerName = $__797.referrerName,
address = $__797.address;
return this.internalLoader_.module(source, referrerName, address);
},
define: function(normalizedName, source) {
var $__797 = $traceurRuntime.assertObject(arguments[2] !== (void 0) ? arguments[2] : {}),
address = $__797.address,
metadata = $__797.metadata;
return this.internalLoader_.define(normalizedName, source, address, metadata);
},
get: function(normalizedName) {
return this.loaderHooks_.get(normalizedName);
},
set: function(normalizedName, module) {
this.loaderHooks_.set(normalizedName, module);
},
normalize: function(name, referrerName, referrerAddress) {
return this.loaderHooks_.normalize(name, referrerName, referrerAddress);
},
locate: function(load) {
return this.loaderHooks_.locate(load);
},
fetch: function(load) {
return this.loaderHooks_.fetch(load);
},
translate: function(load) {
return this.loaderHooks_.translate(load);
},
instantiate: function(load) {
return this.loaderHooks_.instantiate(load);
}
}, {});
;
return {
get Loader() {
return Loader;
},
get LoaderHooks() {
return LoaderHooks;
}
};
});
System.register("traceur@0.0.52/src/WebPageTranscoder", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/WebPageTranscoder";
var Loader = System.get("traceur@0.0.52/src/runtime/Loader").Loader;
var ErrorReporter = System.get("traceur@0.0.52/src/util/ErrorReporter").ErrorReporter;
var InterceptOutputLoaderHooks = System.get("traceur@0.0.52/src/runtime/InterceptOutputLoaderHooks").InterceptOutputLoaderHooks;
var webLoader = System.get("traceur@0.0.52/src/runtime/webLoader").webLoader;
var WebPageTranscoder = function WebPageTranscoder(url) {
this.url = url;
this.numPending_ = 0;
this.numberInlined_ = 0;
};
($traceurRuntime.createClass)(WebPageTranscoder, {
asyncLoad_: function(url, fncOfContent, onScriptsReady) {
var $__802 = this;
this.numPending_++;
webLoader.load(url, (function(content) {
if (content)
fncOfContent(content);
else
console.warn('Failed to load', url);
if (--$__802.numPending_ <= 0)
onScriptsReady();
}), (function(error) {
console.error('WebPageTranscoder FAILED to load ' + url, error.stack || error);
}));
},
addFileFromScriptElement: function(scriptElement, name, content) {
var nameInfo = {
address: name,
referrerName: window.location.href
};
this.loader.module(content, nameInfo).catch(function(error) {
console.error(error.stack || error);
});
},
nextInlineScriptName_: function() {
this.numberInlined_ += 1;
if (!this.inlineScriptNameBase_) {
var segments = this.url.split('.');
segments.pop();
this.inlineScriptNameBase_ = segments.join('.');
}
return this.inlineScriptNameBase_ + '_' + this.numberInlined_ + '.js';
},
addFilesFromScriptElements: function(scriptElements, onScriptsReady) {
for (var i = 0,
length = scriptElements.length; i < length; i++) {
var scriptElement = scriptElements[i];
if (!scriptElement.src) {
var name = this.nextInlineScriptName_();
var content = scriptElement.textContent;
this.addFileFromScriptElement(scriptElement, name, content);
} else {
var name = scriptElement.src;
this.asyncLoad_(name, this.addFileFromScriptElement.bind(this, scriptElement, name), onScriptsReady);
}
}
if (this.numPending_ <= 0)
onScriptsReady();
},
get reporter() {
if (!this.reporter_) {
this.reporter_ = new ErrorReporter();
}
return this.reporter_;
},
get loader() {
if (!this.loader_) {
var loaderHooks = new InterceptOutputLoaderHooks(this.reporter, this.url);
this.loader_ = new Loader(loaderHooks);
}
return this.loader_;
},
putFile: function(file) {
var scriptElement = document.createElement('script');
scriptElement.setAttribute('data-traceur-src-url', file.name);
scriptElement.textContent = file.generatedSource;
var parent = file.scriptElement.parentNode;
parent.insertBefore(scriptElement, file.scriptElement || null);
},
selectAndProcessScripts: function(done) {
var selector = 'script[type="module"]';
var scripts = document.querySelectorAll(selector);
if (!scripts.length) {
done();
return;
}
this.addFilesFromScriptElements(scripts, (function() {
done();
}));
},
run: function() {
var done = arguments[0] !== (void 0) ? arguments[0] : (function() {});
var $__802 = this;
var ready = document.readyState;
if (ready === 'complete' || ready === 'loaded') {
this.selectAndProcessScripts(done);
} else {
document.addEventListener('DOMContentLoaded', (function() {
return $__802.selectAndProcessScripts(done);
}), false);
}
}
}, {});
return {get WebPageTranscoder() {
return WebPageTranscoder;
}};
});
System.register("traceur@0.0.52/src/codegeneration/CloneTreeTransformer", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/CloneTreeTransformer";
var ParseTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/ParseTreeTransformer").ParseTreeTransformer;
var $__805 = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees"),
BindingIdentifier = $__805.BindingIdentifier,
BreakStatement = $__805.BreakStatement,
ContinueStatement = $__805.ContinueStatement,
DebuggerStatement = $__805.DebuggerStatement,
EmptyStatement = $__805.EmptyStatement,
ExportSpecifier = $__805.ExportSpecifier,
ExportStar = $__805.ExportStar,
IdentifierExpression = $__805.IdentifierExpression,
ImportSpecifier = $__805.ImportSpecifier,
LiteralExpression = $__805.LiteralExpression,
ModuleSpecifier = $__805.ModuleSpecifier,
PredefinedType = $__805.PredefinedType,
PropertyNameShorthand = $__805.PropertyNameShorthand,
TemplateLiteralPortion = $__805.TemplateLiteralPortion,
SuperExpression = $__805.SuperExpression,
ThisExpression = $__805.ThisExpression;
var CloneTreeTransformer = function CloneTreeTransformer() {
$traceurRuntime.defaultSuperCall(this, $CloneTreeTransformer.prototype, arguments);
};
var $CloneTreeTransformer = CloneTreeTransformer;
($traceurRuntime.createClass)(CloneTreeTransformer, {
transformBindingIdentifier: function(tree) {
return new BindingIdentifier(tree.location, tree.identifierToken);
},
transformBreakStatement: function(tree) {
return new BreakStatement(tree.location, tree.name);
},
transformContinueStatement: function(tree) {
return new ContinueStatement(tree.location, tree.name);
},
transformDebuggerStatement: function(tree) {
return new DebuggerStatement(tree.location);
},
transformEmptyStatement: function(tree) {
return new EmptyStatement(tree.location);
},
transformExportSpecifier: function(tree) {
return new ExportSpecifier(tree.location, tree.lhs, tree.rhs);
},
transformExportStar: function(tree) {
return new ExportStar(tree.location);
},
transformIdentifierExpression: function(tree) {
return new IdentifierExpression(tree.location, tree.identifierToken);
},
transformImportSpecifier: function(tree) {
return new ImportSpecifier(tree.location, tree.lhs, tree.rhs);
},
transformList: function(list) {
if (!list) {
return null;
} else if (list.length == 0) {
return [];
} else {
return $traceurRuntime.superCall(this, $CloneTreeTransformer.prototype, "transformList", [list]);
}
},
transformLiteralExpression: function(tree) {
return new LiteralExpression(tree.location, tree.literalToken);
},
transformModuleSpecifier: function(tree) {
return new ModuleSpecifier(tree.location, tree.token);
},
transformPredefinedType: function(tree) {
return new PredefinedType(tree.location, tree.typeToken);
},
transformPropertyNameShorthand: function(tree) {
return new PropertyNameShorthand(tree.location, tree.name);
},
transformTemplateLiteralPortion: function(tree) {
return new TemplateLiteralPortion(tree.location, tree.value);
},
transformSuperExpression: function(tree) {
return new SuperExpression(tree.location);
},
transformThisExpression: function(tree) {
return new ThisExpression(tree.location);
}
}, {}, ParseTreeTransformer);
CloneTreeTransformer.cloneTree = function(tree) {
return new CloneTreeTransformer().transformAny(tree);
};
return {get CloneTreeTransformer() {
return CloneTreeTransformer;
}};
});
System.register("traceur@0.0.52/src/codegeneration/module/createModuleEvaluationStatement", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/codegeneration/module/createModuleEvaluationStatement";
var $__807 = Object.freeze(Object.defineProperties(["System.get(", " +'')"], {raw: {value: Object.freeze(["System.get(", " +'')"])}}));
var parseStatement = System.get("traceur@0.0.52/src/codegeneration/PlaceholderParser").parseStatement;
function createModuleEvaluationStatement(normalizedName) {
return parseStatement($__807, normalizedName);
}
return {get createModuleEvaluationStatement() {
return createModuleEvaluationStatement;
}};
});
System.register("traceur@0.0.52/src/runtime/InlineLoaderHooks", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/InlineLoaderHooks";
var LoaderHooks = System.get("traceur@0.0.52/src/runtime/LoaderHooks").LoaderHooks;
var Script = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").Script;
var InlineLoaderHooks = function InlineLoaderHooks(url, elements, fileLoader, moduleStore) {
$traceurRuntime.superCall(this, $InlineLoaderHooks.prototype, "constructor", [null, url, fileLoader, moduleStore]);
this.elements = elements;
};
var $InlineLoaderHooks = InlineLoaderHooks;
($traceurRuntime.createClass)(InlineLoaderHooks, {
evaluateCodeUnit: function(codeUnit) {
var $__812;
var tree = codeUnit.metadata.transformedTree;
($__812 = this.elements).push.apply($__812, $traceurRuntime.spread(tree.scriptItemList));
},
toTree: function() {
return new Script(null, this.elements);
}
}, {}, LoaderHooks);
return {get InlineLoaderHooks() {
return InlineLoaderHooks;
}};
});
System.register("traceur@0.0.52/src/runtime/TraceurLoader", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/TraceurLoader";
var Loader = System.get("traceur@0.0.52/src/runtime/Loader").Loader;
var version = __moduleName.slice(0, __moduleName.indexOf('/'));
var TraceurLoader = function TraceurLoader(loaderHooks) {
if (loaderHooks.translateSynchronous) {
loaderHooks.translate = function(load) {
return new Promise((function(resolve, reject) {
resolve(loaderHooks.translateSynchronous(load));
}));
};
}
$traceurRuntime.superCall(this, $TraceurLoader.prototype, "constructor", [loaderHooks]);
};
var $TraceurLoader = TraceurLoader;
($traceurRuntime.createClass)(TraceurLoader, {
importAll: function(names) {
var $__816 = $traceurRuntime.assertObject(arguments[1] !== (void 0) ? arguments[1] : {}),
referrerName = $__816.referrerName,
address = $__816.address;
var $__814 = this;
return Promise.all(names.map((function(name) {
return $__814.import(name, {
referrerName: referrerName,
address: address
});
})));
},
loadAsScript: function(name) {
var $__816 = $traceurRuntime.assertObject(arguments[1] !== (void 0) ? arguments[1] : {}),
referrerName = $__816.referrerName,
address = $__816.address;
return this.internalLoader_.load(name, referrerName, address, 'script').then((function(codeUnit) {
return codeUnit.result;
}));
},
loadAsScriptAll: function(names) {
var $__816 = $traceurRuntime.assertObject(arguments[1] !== (void 0) ? arguments[1] : {}),
referrerName = $__816.referrerName,
address = $__816.address;
var $__814 = this;
return Promise.all(names.map((function(name) {
return $__814.loadAsScript(name, {
referrerName: referrerName,
address: address
});
})));
},
script: function(source) {
var $__816 = $traceurRuntime.assertObject(arguments[1] !== (void 0) ? arguments[1] : {}),
name = $__816.name,
referrerName = $__816.referrerName,
address = $__816.address;
return this.internalLoader_.script(source, name, referrerName, address);
},
semVerRegExp_: function() {
return /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$/;
},
semverMap: function(normalizedName) {
var slash = normalizedName.indexOf('/');
var version = normalizedName.slice(0, slash);
var at = version.indexOf('@');
if (at !== -1) {
var semver = version.slice(at + 1);
var m = this.semVerRegExp_().exec(semver);
if (m) {
var major = m[1];
var minor = m[2];
var packageName = version.slice(0, at);
var map = Object.create(null);
map[packageName] = version;
map[packageName + '@' + major] = version;
map[packageName + '@' + major + '.' + minor] = version;
}
}
return map;
},
get version() {
return version;
},
sourceMapInfo: function(normalizedName, type) {
return this.internalLoader_.sourceMapInfo(normalizedName, type);
},
register: function(normalizedName, deps, factoryFunction) {
$traceurRuntime.ModuleStore.register(normalizedName, deps, factoryFunction);
},
get baseURL() {
return this.loaderHooks_.baseURL;
},
set baseURL(value) {
this.loaderHooks_.baseURL = value;
}
}, {}, Loader);
return {get TraceurLoader() {
return TraceurLoader;
}};
});
System.register("traceur@0.0.52/src/runtime/System", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/runtime/System";
var ErrorReporter = System.get("traceur@0.0.52/src/util/ErrorReporter").ErrorReporter;
var TraceurLoader = System.get("traceur@0.0.52/src/runtime/TraceurLoader").TraceurLoader;
var LoaderHooks = System.get("traceur@0.0.52/src/runtime/LoaderHooks").LoaderHooks;
var webLoader = System.get("traceur@0.0.52/src/runtime/webLoader").webLoader;
var url;
var fileLoader;
if (typeof window !== 'undefined' && window.location) {
url = window.location.href;
fileLoader = webLoader;
}
var loaderHooks = new LoaderHooks(new ErrorReporter(), url, fileLoader);
var traceurLoader = new TraceurLoader(loaderHooks);
Reflect.global.System = traceurLoader;
;
traceurLoader.map = traceurLoader.semverMap(__moduleName);
return {get System() {
return traceurLoader;
}};
});
System.register("traceur@0.0.52/src/traceur", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/traceur";
System.get("traceur@0.0.52/src/runtime/System");
var $___64_traceur_47_src_47_runtime_47_ModuleStore__ = System.get("@traceur/src/runtime/ModuleStore");
;
var $__traceur_64_0_46_0_46_52_47_src_47_WebPageTranscoder__ = System.get("traceur@0.0.52/src/WebPageTranscoder");
var $__traceur_64_0_46_0_46_52_47_src_47_Options__ = System.get("traceur@0.0.52/src/Options");
var $__821 = System.get("traceur@0.0.52/src/Options"),
addOptions = $__821.addOptions,
CommandOptions = $__821.CommandOptions;
var $__traceur_64_0_46_0_46_52_47_src_47_Compiler__ = System.get("traceur@0.0.52/src/Compiler");
var ErrorReporter = System.get("traceur@0.0.52/src/util/ErrorReporter").ErrorReporter;
var CollectingErrorReporter = System.get("traceur@0.0.52/src/util/CollectingErrorReporter").CollectingErrorReporter;
var util = {
addOptions: addOptions,
CommandOptions: CommandOptions,
ErrorReporter: ErrorReporter,
CollectingErrorReporter: CollectingErrorReporter
};
var Parser = System.get("traceur@0.0.52/src/syntax/Parser").Parser;
var Scanner = System.get("traceur@0.0.52/src/syntax/Scanner").Scanner;
var Script = System.get("traceur@0.0.52/src/syntax/trees/ParseTrees").Script;
var SourceFile = System.get("traceur@0.0.52/src/syntax/SourceFile").SourceFile;
var syntax = {
Parser: Parser,
Scanner: Scanner,
SourceFile: SourceFile,
trees: {Script: Script}
};
var ParseTreeMapWriter = System.get("traceur@0.0.52/src/outputgeneration/ParseTreeMapWriter").ParseTreeMapWriter;
var ParseTreeWriter = System.get("traceur@0.0.52/src/outputgeneration/ParseTreeWriter").ParseTreeWriter;
var SourceMapConsumer = System.get("traceur@0.0.52/src/outputgeneration/SourceMapIntegration").SourceMapConsumer;
var SourceMapGenerator = System.get("traceur@0.0.52/src/outputgeneration/SourceMapIntegration").SourceMapGenerator;
var TreeWriter = System.get("traceur@0.0.52/src/outputgeneration/TreeWriter").TreeWriter;
var outputgeneration = {
ParseTreeMapWriter: ParseTreeMapWriter,
ParseTreeWriter: ParseTreeWriter,
SourceMapConsumer: SourceMapConsumer,
SourceMapGenerator: SourceMapGenerator,
TreeWriter: TreeWriter
};
var AttachModuleNameTransformer = System.get("traceur@0.0.52/src/codegeneration/module/AttachModuleNameTransformer").AttachModuleNameTransformer;
var CloneTreeTransformer = System.get("traceur@0.0.52/src/codegeneration/CloneTreeTransformer").CloneTreeTransformer;
var FromOptionsTransformer = System.get("traceur@0.0.52/src/codegeneration/FromOptionsTransformer").FromOptionsTransformer;
var PureES6Transformer = System.get("traceur@0.0.52/src/codegeneration/PureES6Transformer").PureES6Transformer;
var createModuleEvaluationStatement = System.get("traceur@0.0.52/src/codegeneration/module/createModuleEvaluationStatement").createModuleEvaluationStatement;
var codegeneration = {
CloneTreeTransformer: CloneTreeTransformer,
FromOptionsTransformer: FromOptionsTransformer,
PureES6Transformer: PureES6Transformer,
module: {
AttachModuleNameTransformer: AttachModuleNameTransformer,
createModuleEvaluationStatement: createModuleEvaluationStatement
}
};
var Loader = System.get("traceur@0.0.52/src/runtime/Loader").Loader;
var LoaderHooks = System.get("traceur@0.0.52/src/runtime/LoaderHooks").LoaderHooks;
var InlineLoaderHooks = System.get("traceur@0.0.52/src/runtime/InlineLoaderHooks").InlineLoaderHooks;
var InterceptOutputLoaderHooks = System.get("traceur@0.0.52/src/runtime/InterceptOutputLoaderHooks").InterceptOutputLoaderHooks;
var TraceurLoader = System.get("traceur@0.0.52/src/runtime/TraceurLoader").TraceurLoader;
var runtime = {
InlineLoaderHooks: InlineLoaderHooks,
InterceptOutputLoaderHooks: InterceptOutputLoaderHooks,
Loader: Loader,
LoaderHooks: LoaderHooks,
TraceurLoader: TraceurLoader
};
return {
get ModuleStore() {
return $___64_traceur_47_src_47_runtime_47_ModuleStore__.ModuleStore;
},
get System() {
return System;
},
get WebPageTranscoder() {
return $__traceur_64_0_46_0_46_52_47_src_47_WebPageTranscoder__.WebPageTranscoder;
},
get options() {
return $__traceur_64_0_46_0_46_52_47_src_47_Options__.options;
},
get Compiler() {
return $__traceur_64_0_46_0_46_52_47_src_47_Compiler__.Compiler;
},
get util() {
return util;
},
get syntax() {
return syntax;
},
get outputgeneration() {
return outputgeneration;
},
get codegeneration() {
return codegeneration;
},
get runtime() {
return runtime;
}
};
});
System.register("traceur@0.0.52/src/traceur-import", [], function() {
"use strict";
var __moduleName = "traceur@0.0.52/src/traceur-import";
var traceur = System.get("traceur@0.0.52/src/traceur");
Reflect.global.traceur = traceur;
$traceurRuntime.ModuleStore.set('traceur@', traceur);
return {};
});
System.get("traceur@0.0.52/src/traceur-import" + '');
|
app/containers/HomePage/LeftNav/index.js | SakuB/cloudmusic_web | import React, { Component } from 'react';
import {
NavContainer,
} from './components';
import MenuList from 'components/MenuList';
import CurrentPlay from 'components/CurrentPlay';
class LeftNav extends Component {
render() {
return (
<NavContainer>
<MenuList />
<MenuList />
<CurrentPlay />
</NavContainer>
);
}
}
export default LeftNav;
|
src/components/Tos/Print/MetaDataTable.js | City-of-Helsinki/helerm-ui | import React from 'react';
import PropTypes from 'prop-types';
/**
* @param {string|string[]} value
* @return {string}
*/
const outputValue = value => (Array.isArray(value) ? value.join(', ') : value);
const Table = ({ rows }) => (
<table>
<caption>Metatiedot</caption>
<tbody>
{rows.map(row => {
const [title, ...cells] = row;
return (
<tr key={title}>
<th scope='row'>{title}</th>
{cells.map(value => (
<td key={`${title}.${value}`}>{outputValue(value)}</td>
))}
</tr>
);
})}
</tbody>
</table>
);
const valueShape = PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string)
]);
Table.propTypes = {
rows: PropTypes.arrayOf(PropTypes.arrayOf(valueShape))
};
export default Table;
|
framework/zii/widgets/assets/gridview/jquery.yiigridview.js | arossokha/abcosting | /**
* jQuery Yii GridView plugin file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2010 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
(function ($) {
var selectCheckedRows, methods,
yiiXHR={},
gridSettings = [];
/**
* 1. Selects rows that have checkbox checked (only checkbox that is connected with selecting a row)
* 2. Check if "check all" need to be checked/unchecked
* @return object the jQuery object
*/
selectCheckedRows = function (gridId) {
var settings = gridSettings[gridId],
table = $('#' + gridId).find('.' + settings.tableClass);
table.children('tbody').find('input.select-on-check').filter(':checked').each(function () {
$(this).closest('tr').addClass('selected');
});
table.children('thead').find('th input').filter('[type="checkbox"]').each(function () {
var name = this.name.substring(0, this.name.length - 4) + '[]', //.. remove '_all' and add '[]''
$checks = $("input[name='" + name + "']", table);
this.checked = $checks.length > 0 && $checks.length === $checks.filter(':checked').length;
});
return this;
};
methods = {
/**
* yiiGridView set function.
* @param options map settings for the grid view. Available options are as follows:
* - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response
* - ajaxVar: string, the name of the request variable indicating the ID of the element triggering the AJAX request
* - ajaxType: string, the type (GET or POST) of the AJAX request
* - pagerClass: string, the CSS class for the pager container
* - tableClass: string, the CSS class for the table
* - selectableRows: integer, the number of rows that can be selected
* - updateSelector: string, the selector for choosing which elements can trigger ajax requests
* - beforeAjaxUpdate: function, the function to be called before ajax request is sent
* - afterAjaxUpdate: function, the function to be called after ajax response is received
* - ajaxUpdateError: function, the function to be called if an ajax error occurs
* - selectionChanged: function, the function to be called after the row selection is changed
* @return object the jQuery object
*/
init: function (options) {
var settings = $.extend({
ajaxUpdate: [],
ajaxVar: 'ajax',
ajaxType: 'GET',
pagerClass: 'pager',
loadingClass: 'loading',
filterClass: 'filters',
tableClass: 'items',
selectableRows: 1
// updateSelector: '#id .pager a, '#id .grid thead th a',
// beforeAjaxUpdate: function (id) {},
// afterAjaxUpdate: function (id, data) {},
// selectionChanged: function (id) {},
// url: 'ajax request URL'
}, options || {});
settings.tableClass = settings.tableClass.replace(/\s+/g, '.');
return this.each(function () {
var eventType,
$grid = $(this),
id = $grid.attr('id'),
pagerSelector = '#' + id + ' .' + settings.pagerClass.replace(/\s+/g, '.') + ' a',
sortSelector = '#' + id + ' .' + settings.tableClass + ' thead th a.sort-link',
inputSelector = '#' + id + ' .' + settings.filterClass + ' input, ' + '#' + id + ' .' + settings.filterClass + ' select';
settings.updateSelector = settings.updateSelector
.replace('{page}', pagerSelector)
.replace('{sort}', sortSelector);
settings.filterSelector = settings.filterSelector
.replace('{filter}', inputSelector);
gridSettings[id] = settings;
if (settings.ajaxUpdate.length > 0) {
$(document).on('click.yiiGridView', settings.updateSelector, function () {
// Check to see if History.js is enabled for our Browser
if (settings.enableHistory && window.History.enabled) {
// Ajaxify this link
var url = $(this).attr('href').split('?'),
params = $.deparam.querystring('?'+ (url[1] || ''));
delete params[settings.ajaxVar];
window.History.pushState(null, document.title, decodeURIComponent($.param.querystring(url[0], params)));
} else {
$('#' + id).yiiGridView('update', {url: $(this).attr('href')});
}
return false;
});
}
$(document).on('change.yiiGridView keydown.yiiGridView', settings.filterSelector, function (event) {
if (event.type === 'keydown') {
if (event.keyCode !== 13) {
return; // only react to enter key
} else {
eventType = 'keydown';
}
} else {
// prevent processing for both keydown and change events
if (eventType === 'keydown') {
eventType = '';
return;
}
}
var data = $(settings.filterSelector).serialize();
if (settings.pageVar !== undefined) {
data += '&' + settings.pageVar + '=1';
}
if (settings.enableHistory && settings.ajaxUpdate !== false && window.History.enabled) {
// Ajaxify this link
var url = $('#' + id).yiiGridView('getUrl'),
params = $.deparam.querystring($.param.querystring(url, data));
delete params[settings.ajaxVar];
window.History.pushState(null, document.title, decodeURIComponent($.param.querystring(url.substr(0, url.indexOf('?')), params)));
} else {
$('#' + id).yiiGridView('update', {data: data});
}
return false;
});
if (settings.enableHistory && settings.ajaxUpdate !== false && window.History.enabled) {
$(window).bind('statechange', function() { // Note: We are using statechange instead of popstate
var State = window.History.getState(); // Note: We are using History.getState() instead of event.state
$('#' + id).yiiGridView('update', {url: State.url});
});
}
if (settings.selectableRows > 0) {
selectCheckedRows(this.id);
$(document).on('click.yiiGridView', '#' + id + ' .' + settings.tableClass + ' > tbody > tr', function (e) {
var $currentGrid, $row, isRowSelected, $checks,
$target = $(e.target);
if ($target.closest('td').is('.empty,.button-column') || (e.target.type === 'checkbox' && !$target.hasClass('select-on-check'))) {
return;
}
$row = $(this);
$currentGrid = $('#' + id);
$checks = $('input.select-on-check', $currentGrid);
isRowSelected = $row.toggleClass('selected').hasClass('selected');
if (settings.selectableRows === 1) {
$row.siblings().removeClass('selected');
$checks.prop('checked', false);
}
$('input.select-on-check', $row).prop('checked', isRowSelected);
$("input.select-on-check-all", $currentGrid).prop('checked', $checks.length === $checks.filter(':checked').length);
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
if (settings.selectableRows > 1) {
$(document).on('click.yiiGridView', '#' + id + ' .select-on-check-all', function () {
var $currentGrid = $('#' + id),
$checks = $('input.select-on-check', $currentGrid),
$checksAll = $('input.select-on-check-all', $currentGrid),
$rows = $currentGrid.find('.' + settings.tableClass).children('tbody').children();
if (this.checked) {
$rows.addClass('selected');
$checks.prop('checked', true);
$checksAll.prop('checked', true);
} else {
$rows.removeClass('selected');
$checks.prop('checked', false);
$checksAll.prop('checked', false);
}
if (settings.selectionChanged !== undefined) {
settings.selectionChanged(id);
}
});
}
} else {
$(document).on('click.yiiGridView', '#' + id + ' .select-on-check', false);
}
});
},
/**
* Returns the key value for the specified row
* @param row integer the row number (zero-based index)
* @return string the key value
*/
getKey: function (row) {
return this.children('.keys').children('span').eq(row).text();
},
/**
* Returns the URL that generates the grid view content.
* @return string the URL that generates the grid view content.
*/
getUrl: function () {
var sUrl = gridSettings[this.attr('id')].url;
return sUrl || this.children('.keys').attr('title');
},
/**
* Returns the jQuery collection of the cells in the specified row.
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
getRow: function (row) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.find('.' + sClass).children('tbody').children('tr').eq(row).children();
},
/**
* Returns the jQuery collection of the cells in the specified column.
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
getColumn: function (column) {
var sClass = gridSettings[this.attr('id')].tableClass;
return this.find('.' + sClass).children('tbody').children('tr').children('td:nth-child(' + (column + 1) + ')');
},
/**
* Performs an AJAX-based update of the grid view contents.
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
* @return object the jQuery object
*/
update: function (options) {
var customError;
if (options && options.error !== undefined) {
customError = options.error;
delete options.error;
}
return this.each(function () {
var $form,
$grid = $(this),
id = $grid.attr('id'),
settings = gridSettings[id];
options = $.extend({
type: settings.ajaxType,
url: $grid.yiiGridView('getUrl'),
success: function (data) {
var $data = $('<div>' + data + '</div>');
$.each(settings.ajaxUpdate, function (i, el) {
var updateId = '#' + el;
$(updateId).replaceWith($(updateId, $data));
});
if (settings.afterAjaxUpdate !== undefined) {
settings.afterAjaxUpdate(id, data);
}
if (settings.selectableRows > 0) {
selectCheckedRows(id);
}
},
complete: function () {
yiiXHR[id] = null;
$grid.removeClass(settings.loadingClass);
},
error: function (XHR, textStatus, errorThrown) {
var ret, err;
if (XHR.readyState === 0 || XHR.status === 0) {
return;
}
if (customError !== undefined) {
ret = customError(XHR);
if (ret !== undefined && !ret) {
return;
}
}
switch (textStatus) {
case 'timeout':
err = 'The request timed out!';
break;
case 'parsererror':
err = 'Parser error!';
break;
case 'error':
if (XHR.status && !/^\s*$/.test(XHR.status)) {
err = 'Error ' + XHR.status;
} else {
err = 'Error';
}
if (XHR.responseText && !/^\s*$/.test(XHR.responseText)) {
err = err + ': ' + XHR.responseText;
}
break;
}
if (settings.ajaxUpdateError !== undefined) {
settings.ajaxUpdateError(XHR, textStatus, errorThrown, err);
} else if (err) {
alert(err);
}
}
}, options || {});
if (options.type === 'GET') {
if (options.data !== undefined) {
options.url = $.param.querystring(options.url, options.data);
options.data = {};
}
} else {
if (options.data === undefined) {
options.data = $(settings.filterSelector).serialize();
}
}
if(yiiXHR[id] != null){
yiiXHR[id].abort();
}
//class must be added after yiiXHR.abort otherwise ajax.error will remove it
$grid.addClass(settings.loadingClass);
if (settings.ajaxUpdate !== false) {
if(settings.ajaxVar) {
options.url = $.param.querystring(options.url, settings.ajaxVar + '=' + id);
}
if (settings.beforeAjaxUpdate !== undefined) {
settings.beforeAjaxUpdate(id, options);
}
yiiXHR[id] = $.ajax(options);
} else { // non-ajax mode
if (options.type === 'GET') {
window.location.href = options.url;
} else { // POST mode
$form = $('<form action="' + options.url + '" method="post"></form>').appendTo('body');
if (options.data === undefined) {
options.data = {};
}
if (options.data.returnUrl === undefined) {
options.data.returnUrl = window.location.href;
}
$.each(options.data, function (name, value) {
$form.append($('<input type="hidden" name="t" value="" />').attr('name', name).val(value));
});
$form.submit();
}
}
});
},
/**
* Returns the key values of the currently selected rows.
* @return array the key values of the currently selected rows.
*/
getSelection: function () {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
selection = [];
this.find('.' + settings.tableClass).children('tbody').children().each(function (i) {
if ($(this).hasClass('selected')) {
selection.push(keys.eq(i).text());
}
});
return selection;
},
/**
* Returns the key values of the currently checked rows.
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
getChecked: function (column_id) {
var settings = gridSettings[this.attr('id')],
keys = this.find('.keys span'),
checked = [];
if (column_id.substring(column_id.length - 2) !== '[]') {
column_id = column_id + '[]';
}
this.find('.' + settings.tableClass).children('tbody').children('tr').children('td').children('input[name="' + column_id + '"]').each(function (i) {
if (this.checked) {
checked.push(keys.eq(i).text());
}
});
return checked;
}
};
$.fn.yiiGridView = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiGridView');
return false;
}
};
/******************************************************************************
*** DEPRECATED METHODS
*** used before Yii 1.1.9
******************************************************************************/
$.fn.yiiGridView.settings = gridSettings;
/**
* Returns the key value for the specified row
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return string the key value
*/
$.fn.yiiGridView.getKey = function (id, row) {
return $('#' + id).yiiGridView('getKey', row);
};
/**
* Returns the URL that generates the grid view content.
* @param id string the ID of the grid view container
* @return string the URL that generates the grid view content.
*/
$.fn.yiiGridView.getUrl = function (id) {
return $('#' + id).yiiGridView('getUrl');
};
/**
* Returns the jQuery collection of the cells in the specified row.
* @param id string the ID of the grid view container
* @param row integer the row number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified row.
*/
$.fn.yiiGridView.getRow = function (id, row) {
return $('#' + id).yiiGridView('getRow', row);
};
/**
* Returns the jQuery collection of the cells in the specified column.
* @param id string the ID of the grid view container
* @param column integer the column number (zero-based index)
* @return jQuery the jQuery collection of the cells in the specified column.
*/
$.fn.yiiGridView.getColumn = function (id, column) {
return $('#' + id).yiiGridView('getColumn', column);
};
/**
* Performs an AJAX-based update of the grid view contents.
* @param id string the ID of the grid view container
* @param options map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
*/
$.fn.yiiGridView.update = function (id, options) {
$('#' + id).yiiGridView('update', options);
};
/**
* Returns the key values of the currently selected rows.
* @param id string the ID of the grid view container
* @return array the key values of the currently selected rows.
*/
$.fn.yiiGridView.getSelection = function (id) {
return $('#' + id).yiiGridView('getSelection');
};
/**
* Returns the key values of the currently checked rows.
* @param id string the ID of the grid view container
* @param column_id string the ID of the column
* @return array the key values of the currently checked rows.
*/
$.fn.yiiGridView.getChecked = function (id, column_id) {
return $('#' + id).yiiGridView('getChecked', column_id);
};
})(jQuery);
|
frontend/webpack.config.js | auronzhong/pratice-node-project | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'./entry.js',
],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/build'
},
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css'
}, {
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loaders: ['react-hot', 'babel'],
}, {
test: /\.(woff|woff2)$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf$/,
loader: "file-loader"
}, {
test: /\.eot$/,
loader: "file-loader"
}, {
test: /\.svg$/,
loader: "file-loader"
}, {
test: /\/bootstrap\/js\//,
loader: 'imports?jQuery=jquery'
}]
},
devServer: {
contentBase: __dirname,
port: 3000,
inline: true,
historyApiFallback: true,
stats: {
colors: true
},
hot: true,
proxy: {
'*': 'http://127.0.0.1:3001',
}
},
babel: {
presets: ['react', 'es2015']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
};
|
ajax/libs/rxjs/2.4.1/rx.lite.js | kristoferjoseph/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) {
var len = arr.length, a = new Array(len);
for(var i = 0; i < len; i++) { a[i] = arr[i]; }
return a;
}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
if (!item.isCancelled()) {
!item.isCancelled() && item.invoke();
}
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
var onGlobalPostMessage = function (event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function(err) { o.onError(err); },
self)
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return observer.onError(ex);
}
if (currentItem.done) {
if (lastException !== null) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
if (selector) {
var selectorFn = bindCallback(selector, thisArg, 3);
}
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ToArrayObserver(observer));
};
return ToArrayObservable;
}(ObservableBase));
function ToArrayObserver(observer) {
this.observer = observer;
this.a = [];
this.isStopped = false;
}
ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
ToArrayObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ToArrayObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onNext(this.a);
this.observer.onCompleted();
}
};
ToArrayObserver.prototype.dispose = function () { this.isStopped = true; }
ToArrayObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.count = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.count, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
//deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return enumerableOf(args).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
return MergeAllObservable;
}(ObservableBase));
var MergeAllObserver = (function() {
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
return observer.onError(e);
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, this);
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
}
if (hasCurrentKey) {
try {
var comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
tapObserver.onNext(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
try {
tapObserver.onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}, function () {
try {
tapObserver.onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
});
}, this);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
var self = this;
return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg)
};
MapObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new MapObserver(observer, this.selector, this));
};
return MapObservable;
}(ObservableBase));
function MapObserver(observer, selector, source) {
this.observer = observer;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector).call(this, x, this.i++, this.source);
if (result === errorObj) {
return this.observer.onError(result.e);
}
this.observer.onNext(result);
/*try {
var result = this.selector(x, this.i++, this.source);
} catch (e) {
return this.observer.onError(e);
}
this.observer.onNext(result);*/
};
MapObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
MapObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
MapObserver.prototype.dispose = function() { this.isStopped = true; };
MapObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new FilterObserver(observer, this.predicate, this));
};
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
var self = this;
return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.observer.onError(shouldYield.e);
}
shouldYield && this.observer.onNext(x);
};
FilterObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
FilterObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
FilterObserver.prototype.dispose = function() { this.isStopped = true; };
FilterObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return new AnonymousObservable(function (observer) {
function handler() {
var results = arguments;
if (selector) {
try {
results = selector(results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var len = arguments.length, results = new Array(len - 1);
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (selector) {
try {
results = selector(results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette, Ember.js
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count);
self(count + 1, d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
//deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
(!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted();
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
(!this.enableQueue || this.queue.length === 0) && this.subject.onError(error);
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(value);
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
return this.queue.length !== 0 ?
{ numberOfItems: numberOfItems, returnValue: true } :
{ numberOfItems: numberOfItems, returnValue: false };
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
/**
* Used to pause and resume streams.
*/
Rx.Pauser = (function (__super__) {
inherits(Pauser, __super__);
function Pauser() {
__super__.call(this);
}
/**
* Pauses the underlying sequence.
*/
Pauser.prototype.pause = function () { this.onNext(false); };
/**
* Resumes the underlying sequence.
*/
Pauser.prototype.resume = function () { this.onNext(true); };
return Pauser;
}(Subject));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
src/PageItem.js | leozdgao/react-bootstrap | import React from 'react';
import classNames from 'classnames';
const PageItem = React.createClass({
propTypes: {
href: React.PropTypes.string,
target: React.PropTypes.string,
title: React.PropTypes.string,
disabled: React.PropTypes.bool,
previous: React.PropTypes.bool,
next: React.PropTypes.bool,
onSelect: React.PropTypes.func,
eventKey: React.PropTypes.any
},
getDefaultProps() {
return {
href: '#'
};
},
render() {
let classes = {
'disabled': this.props.disabled,
'previous': this.props.previous,
'next': this.props.next
};
return (
<li
{...this.props}
className={classNames(this.props.className, classes)}>
<a
href={this.props.href}
title={this.props.title}
target={this.props.target}
onClick={this.handleSelect}
ref="anchor">
{this.props.children}
</a>
</li>
);
},
handleSelect(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
export default PageItem;
|
src/App.js | zsl99a/like-time-down | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import ShowTime from './components/like-show-time'
import ShowDate from './components/like-show-date'
import TimeDown from './components/like-time-down'
class App extends Component {
onStart () {
console.log('Start')
}
onEnd () {
console.log('End')
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<ShowTime time={12 * 24 * 60 * 60 * 1000 + 227 * 60 * 1000 + 31 * 1000} className="myclassname" />
<ShowDate time={12 * 24 * 60 * 60 * 1000 + 227 * 60 * 1000 + 31 * 1000} />
<TimeDown start={Date.now() - 1000 * 3} end={Date.now() + 1000 * 8} now={Date.now()}
onStart={() => this.onStart()} onEnd={() => this.onEnd()} />
</div>
);
}
}
export default App;
|
src/browser/app/Header.js | xiankai/triple-triad-solver | /* @flow */
import type { State } from '../../common/types';
import React from 'react';
import linksMessages from '../../common/app/linksMessages';
import { FormattedMessage } from 'react-intl';
import { Link, Space, Toolbar } from '../app/components';
import { connect } from 'react-redux';
const styles = {
toolbar: {
flexWrap: 'wrap',
},
prefetch: {
display: 'none',
},
};
const Header = () => (
<Toolbar style={styles.toolbar}>
<Link bold inverted exactly to="/">
<FormattedMessage {...linksMessages.home} />
</Link>
<Space x={2} />
<Link bold inverted to="/cards">
<FormattedMessage {...linksMessages.cards} />
</Link>
<Space x={2} />
<Link bold inverted to="/stack">
<FormattedMessage {...linksMessages.stack} />
</Link>
</Toolbar>
);
Header.propTypes = {
viewer: React.PropTypes.object,
};
export default connect(
(state: State) => ({
viewer: state.users.viewer,
}),
)(Header);
|
node_modules/react-icons/io/battery-full.js | bengimbel/Solstice-React-Contacts-Project |
import React from 'react'
import Icon from 'react-icon-base'
const IoBatteryFull = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m34.2 15c0.5 0 0.8 0.3 0.8 0.8v8.4c0 0.5-0.3 0.8-0.8 0.8h-2.9v4.2c0 0.5-0.3 0.8-0.8 0.8h-29.7c-0.5 0-0.8-0.3-0.8-0.8v-18.4c0-0.5 0.3-0.8 0.8-0.8h29.7c0.5 0 0.8 0.3 0.8 0.8v4.2h2.9z"/></g>
</Icon>
)
export default IoBatteryFull
|
lib/renderables/modelView.js | randylubin/fission | 'use strict';
var Model = require('ampersand-model');
var React = require('react');
var merge = require('lodash.merge');
var view = require('./view');
var constructModel = require('../util/ensureInstance').model;
module.exports = function(config) {
if (config == null) {
throw new Error('config parameter is required');
}
var configModel = config.model;
delete config.model;
var ModelViewMixin = {
displayName: 'modelView',
propTypes: {
index: React.PropTypes.number,
model: React.PropTypes.oneOfType([
React.PropTypes.func,
React.PropTypes.object,
React.PropTypes.instanceOf(Model)
]),
data: React.PropTypes.object,
routeIdAttribute: React.PropTypes.string,
query: React.PropTypes.object
},
// most options can be passed via config or props
// props takes precedence
getDefaultProps: function(){
return {
model: configModel,
data: config.data,
routeIdAttribute: (config.routeIdAttribute || 'id')
};
},
componentWillMount: function() {
this._initialize(this.props);
},
componentWillReceiveProps: function(nextProps) {
if (!this.model) {
return;
}
// TODO: check if routeIdAttribute changed
// if the next route id changed, redo the model
// sometimes views get recycled
var nextRouteIdAttribute = this.getParams()[nextProps.routeIdAttribute];
if (nextRouteIdAttribute && nextRouteIdAttribute !== this.model.getId()) {
this._initialize(nextProps);
}
},
_modelFetchFailed: function(m, res) {
var notFound = res.status === 404 || res.status === 204;
var handled404 = notFound && this.modelNotFound;
if (this.modelFetchFailed) {
this.modelFetchFailed.apply(this, arguments);
}
if (handled404) {
this.modelNotFound.apply(this, arguments);
}
this.model = null;
if (!this.modelFetchFailed && !handled404) {
throw new Error('Model fetch failed with a ' + res.status);
}
},
_initialize: function(props) {
var routeIdAttribute = this.getParams()[props.routeIdAttribute];
var options = props;
if (routeIdAttribute) {
options = merge({
id: routeIdAttribute
}, options);
}
var model = constructModel(props.model, options);
// no model specified in props or config
if (!model) {
throw new Error('modelView never got a model');
}
var setModel = (function(m, res){
if (res && res.status !== 200) {
return this._modelFetchFailed(model, res);
}
this.model = model;
this.model.on('change', this.tryUpdate);
if (this.modelDidFetch) {
this.modelDidFetch();
}
if (model._needsInitialFetch) {
this.tryUpdate();
}
}).bind(this);
if (model._needsInitialFetch) {
if (this.modelWillFetch) {
this.modelWillFetch(model);
}
model.fetch({
success: setModel,
error: this._modelFetchFailed
});
} else {
setModel();
}
}
};
return view(config, [ModelViewMixin]);
}; |
ajax/libs/react/0.14.7/react.js | him2him2/cdnjs | /**
* React v0.14.7
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-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 React
*/
'use strict';
var ReactDOM = _dereq_(35);
var ReactDOMServer = _dereq_(45);
var ReactIsomorphic = _dereq_(63);
var assign = _dereq_(23);
var deprecated = _dereq_(106);
// `version` will be added here by ReactIsomorphic.
var React = {};
assign(React, ReactIsomorphic);
assign(React, {
// ReactDOM
findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode),
render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render),
unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode),
// ReactDOMServer
renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString),
renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup)
});
React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM;
React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer;
module.exports = React;
},{"106":106,"23":23,"35":35,"45":45,"63":63}],2:[function(_dereq_,module,exports){
/**
* 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 AutoFocusUtils
* @typechecks static-only
*/
'use strict';
var ReactMount = _dereq_(65);
var findDOMNode = _dereq_(108);
var focusNode = _dereq_(138);
var Mixin = {
componentDidMount: function () {
if (this.props.autoFocus) {
focusNode(findDOMNode(this));
}
}
};
var AutoFocusUtils = {
Mixin: Mixin,
focusDOMComponent: function () {
focusNode(ReactMount.getNode(this._rootNodeID));
}
};
module.exports = AutoFocusUtils;
},{"108":108,"138":138,"65":65}],3:[function(_dereq_,module,exports){
/**
* 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 BeforeInputEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(19);
var ExecutionEnvironment = _dereq_(130);
var FallbackCompositionState = _dereq_(20);
var SyntheticCompositionEvent = _dereq_(90);
var SyntheticInputEvent = _dereq_(94);
var keyOf = _dereq_(148);
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
var topLevelTypes = EventConstants.topLevelTypes;
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({ onBeforeInput: null }),
captured: keyOf({ onBeforeInputCapture: null })
},
dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste]
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionEnd: null }),
captured: keyOf({ onCompositionEndCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionStart: null }),
captured: keyOf({ onCompositionStartCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionUpdate: null }),
captured: keyOf({ onCompositionUpdateCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
}
};
// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
// Track the current IME composition fallback object, if any.
var currentComposition = null;
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topCompositionEnd:
return getDataFromCustomEvent(nativeEvent);
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
if (currentComposition) {
if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
return chars;
}
return null;
}
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
return String.fromCharCode(nativeEvent.which);
}
return null;
case topLevelTypes.topCompositionEnd:
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)];
}
};
module.exports = BeforeInputEventPlugin;
},{"130":130,"148":148,"15":15,"19":19,"20":20,"90":90,"94":94}],4:[function(_dereq_,module,exports){
/**
* 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 CSSProperty
*/
'use strict';
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
stopOpacity: true,
strokeDashoffset: true,
strokeOpacity: true,
strokeWidth: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: true,
backgroundColor: true,
backgroundImage: true,
backgroundPositionX: true,
backgroundPositionY: true,
backgroundRepeat: true
},
backgroundPosition: {
backgroundPositionX: true,
backgroundPositionY: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
},
outline: {
outlineWidth: true,
outlineStyle: true,
outlineColor: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],5:[function(_dereq_,module,exports){
/**
* 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 CSSPropertyOperations
* @typechecks static-only
*/
'use strict';
var CSSProperty = _dereq_(4);
var ExecutionEnvironment = _dereq_(130);
var ReactPerf = _dereq_(71);
var camelizeStyleName = _dereq_(132);
var dangerousStyleValue = _dereq_(105);
var hyphenateStyleName = _dereq_(143);
var memoizeStringOnly = _dereq_(150);
var warning = _dereq_(155);
var processStyleName = memoizeStringOnly(function (styleName) {
return hyphenateStyleName(styleName);
});
var hasShorthandPropertyBug = false;
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
var tempStyle = document.createElement('div').style;
try {
// IE8 throws "Invalid argument." if resetting shorthand style properties.
tempStyle.font = '';
} catch (e) {
hasShorthandPropertyBug = true;
}
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if ("development" !== 'production') {
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnHyphenatedStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
"development" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined;
};
var warnBadVendoredStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
"development" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined;
};
var warnStyleValueWithSemicolon = function (name, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
"development" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined;
};
/**
* @param {string} name
* @param {*} value
*/
var warnValidStyle = function (name, value) {
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value);
}
};
}
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @return {?string}
*/
createMarkupForStyles: function (styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if ("development" !== 'production') {
warnValidStyle(styleName, styleValue);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function (node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if ("development" !== 'production') {
warnValidStyle(styleName, styles[styleName]);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleName === 'float') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', {
setValueForStyles: 'setValueForStyles'
});
module.exports = CSSPropertyOperations;
},{"105":105,"130":130,"132":132,"143":143,"150":150,"155":155,"4":4,"71":71}],6:[function(_dereq_,module,exports){
/**
* 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 CallbackQueue
*/
'use strict';
var PooledClass = _dereq_(24);
var assign = _dereq_(23);
var invariant = _dereq_(144);
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null;
this._contexts = null;
}
assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function (callback, context) {
this._callbacks = this._callbacks || [];
this._contexts = this._contexts || [];
this._callbacks.push(callback);
this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function () {
var callbacks = this._callbacks;
var contexts = this._contexts;
if (callbacks) {
!(callbacks.length === contexts.length) ? "development" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined;
this._callbacks = null;
this._contexts = null;
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function () {
this._callbacks = null;
this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function () {
this.reset();
}
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
},{"144":144,"23":23,"24":24}],7:[function(_dereq_,module,exports){
/**
* 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 ChangeEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(16);
var EventPropagators = _dereq_(19);
var ExecutionEnvironment = _dereq_(130);
var ReactUpdates = _dereq_(83);
var SyntheticEvent = _dereq_(92);
var getEventTarget = _dereq_(114);
var isEventSupported = _dereq_(119);
var isTextInputElement = _dereq_(120);
var keyOf = _dereq_(148);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({ onChange: null }),
captured: keyOf({ onChangeCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange]
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementID = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent));
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue(false);
}
function startWatchingForChangeEventIE8(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementID = null;
}
function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topChange) {
return topLevelTargetID;
}
}
function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events
isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9);
}
/**
* (For old IE.) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function () {
return activeElementValueProp.get.call(this);
},
set: function (val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For old IE.) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
// on DOM elements
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For old IE.) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For old IE.) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return topLevelTargetID;
}
}
// For IE8 and IE9.
function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementID;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}
function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topClick) {
return topLevelTargetID;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var getTargetIDFunc, handleEventFunc;
if (shouldUseChangeEvent(topLevelTarget)) {
if (doesChangeEventBubble) {
getTargetIDFunc = getTargetIDForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(topLevelTarget)) {
if (isInputEventSupported) {
getTargetIDFunc = getTargetIDForInputEvent;
} else {
getTargetIDFunc = getTargetIDForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(topLevelTarget)) {
getTargetIDFunc = getTargetIDForClickEvent;
}
if (getTargetIDFunc) {
var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID);
if (targetID) {
var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget);
event.type = 'change';
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID);
}
}
};
module.exports = ChangeEventPlugin;
},{"114":114,"119":119,"120":120,"130":130,"148":148,"15":15,"16":16,"19":19,"83":83,"92":92}],8:[function(_dereq_,module,exports){
/**
* 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 ClientReactRootIndex
* @typechecks
*/
'use strict';
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function () {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
},{}],9:[function(_dereq_,module,exports){
/**
* 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 DOMChildrenOperations
* @typechecks static-only
*/
'use strict';
var Danger = _dereq_(12);
var ReactMultiChildUpdateTypes = _dereq_(67);
var ReactPerf = _dereq_(71);
var setInnerHTML = _dereq_(124);
var setTextContent = _dereq_(125);
var invariant = _dereq_(144);
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
function insertChildAt(parentNode, childNode, index) {
// By exploiting arrays returning `undefined` for an undefined index, we can
// rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. However, using `undefined` is not allowed by all
// browsers so we must replace it with `null`.
// fix render order error in safari
// IE8 will throw error when index out of list size.
var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index);
parentNode.insertBefore(childNode, beforeChild);
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: setTextContent,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markupList List of markup strings.
* @internal
*/
processUpdates: function (updates, markupList) {
var update;
// Mapping from parent IDs to initial child orderings.
var initialChildren = null;
// List of children that will be moved or removed.
var updatedChildren = null;
for (var i = 0; i < updates.length; i++) {
update = updates[i];
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
var updatedIndex = update.fromIndex;
var updatedChild = update.parentNode.childNodes[updatedIndex];
var parentID = update.parentID;
!updatedChild ? "development" !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined;
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup;
// markupList is either a list of markup or just a list of elements
if (markupList.length && typeof markupList[0] === 'string') {
renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
} else {
renderedMarkup = markupList;
}
// Remove updated children first so that `toIndex` is consistent.
if (updatedChildren) {
for (var j = 0; j < updatedChildren.length; j++) {
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
}
}
for (var k = 0; k < updates.length; k++) {
update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex);
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex);
break;
case ReactMultiChildUpdateTypes.SET_MARKUP:
setInnerHTML(update.parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(update.parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', {
updateTextContent: 'updateTextContent'
});
module.exports = DOMChildrenOperations;
},{"12":12,"124":124,"125":125,"144":144,"67":67,"71":71}],10:[function(_dereq_,module,exports){
/**
* 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 DOMProperty
* @typechecks static-only
*/
'use strict';
var invariant = _dereq_(144);
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_ATTRIBUTE: 0x1,
MUST_USE_PROPERTY: 0x2,
HAS_SIDE_EFFECTS: 0x4,
HAS_BOOLEAN_VALUE: 0x8,
HAS_NUMERIC_VALUE: 0x10,
HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
* attribute namespace URL. (Attribute names not specified use no namespace.)
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function (domPropertyConfig) {
var Injection = DOMPropertyInjection;
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
}
for (var propName in Properties) {
!!DOMProperty.properties.hasOwnProperty(propName) ? "development" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined;
var lowerCased = propName.toLowerCase();
var propConfig = Properties[propName];
var propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE),
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS),
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
};
!(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined;
!(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined;
!(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined;
if ("development" !== 'production') {
DOMProperty.getPossibleStandardName[lowerCased] = propName;
}
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
propertyInfo.attributeName = attributeName;
if ("development" !== 'production') {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
}
if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
}
if (DOMPropertyNames.hasOwnProperty(propName)) {
propertyInfo.propertyName = DOMPropertyNames[propName];
}
if (DOMMutationMethods.hasOwnProperty(propName)) {
propertyInfo.mutationMethod = DOMMutationMethods[propName];
}
DOMProperty.properties[propName] = propertyInfo;
}
}
};
var defaultValueCache = {};
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
/**
* Map from property "standard name" to an object with info about how to set
* the property in the DOM. Each object contains:
*
* attributeName:
* Used when rendering markup or with `*Attribute()`.
* attributeNamespace
* propertyName:
* Used on DOM node instances. (This includes properties that mutate due to
* external factors.)
* mutationMethod:
* If non-null, used instead of the property or `setAttribute()` after
* initial render.
* mustUseAttribute:
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* hasSideEffects:
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. If true, we read from
* the DOM before updating to ensure that the value is only set if it has
* changed.
* hasBooleanValue:
* Whether the property should be removed when set to a falsey value.
* hasNumericValue:
* Whether the property must be numeric or parse as a numeric and should be
* removed when set to a falsey value.
* hasPositiveNumericValue:
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* hasOverloadedBooleanValue:
* Whether the property can be used as a flag as well as with a value.
* Removed when strictly equal to false; present without a value when
* strictly equal to true; present with a value otherwise.
*/
properties: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties. Available only in __DEV__.
* @type {Object}
*/
getPossibleStandardName: "development" !== 'production' ? {} : null,
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function (attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
/**
* Returns the default property value for a DOM property (i.e., not an
* attribute). Most default values are '' or false, but not all. Worse yet,
* some (in particular, `type`) vary depending on the type of element.
*
* TODO: Is it better to grab all the possible properties when creating an
* element to avoid having to create the same element twice?
*/
getDefaultValueForProperty: function (nodeName, prop) {
var nodeDefaults = defaultValueCache[nodeName];
var testElement;
if (!nodeDefaults) {
defaultValueCache[nodeName] = nodeDefaults = {};
}
if (!(prop in nodeDefaults)) {
testElement = document.createElement(nodeName);
nodeDefaults[prop] = testElement[prop];
}
return nodeDefaults[prop];
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
},{"144":144}],11:[function(_dereq_,module,exports){
/**
* 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 DOMPropertyOperations
* @typechecks static-only
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactPerf = _dereq_(71);
var quoteAttributeValueForBrowser = _dereq_(122);
var warning = _dereq_(155);
// Simplified subset
var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/;
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (validatedAttributeNameCache.hasOwnProperty(attributeName)) {
return true;
}
if (illegalAttributeNameCache.hasOwnProperty(attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
"development" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
if ("development" !== 'production') {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function (name) {
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
"development" !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined;
};
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function (id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function (node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function (name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.attributeName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
} else if ("development" !== 'production') {
warnUnknownProperty(name);
}
return null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function (name, value) {
if (!isAttributeNameSafe(name) || value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function (node, name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(propertyInfo, value)) {
this.deleteValueForProperty(node, name);
} else if (propertyInfo.mustUseAttribute) {
var attributeName = propertyInfo.attributeName;
var namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (namespace) {
node.setAttributeNS(namespace, attributeName, '' + value);
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
node.setAttribute(attributeName, '');
} else {
node.setAttribute(attributeName, '' + value);
}
} else {
var propName = propertyInfo.propertyName;
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
// property type before comparing; only `value` does and is string.
if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
} else if ("development" !== 'production') {
warnUnknownProperty(name);
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function (node, name) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseAttribute) {
node.removeAttribute(propertyInfo.attributeName);
} else {
var propName = propertyInfo.propertyName;
var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName);
if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) {
node[propName] = defaultValue;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if ("development" !== 'production') {
warnUnknownProperty(name);
}
}
};
ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', {
setValueForProperty: 'setValueForProperty',
setValueForAttribute: 'setValueForAttribute',
deleteValueForProperty: 'deleteValueForProperty'
});
module.exports = DOMPropertyOperations;
},{"10":10,"122":122,"155":155,"71":71}],12:[function(_dereq_,module,exports){
/**
* 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 Danger
* @typechecks static-only
*/
'use strict';
var ExecutionEnvironment = _dereq_(130);
var createNodesFromMarkup = _dereq_(135);
var emptyFunction = _dereq_(136);
var getMarkupWrap = _dereq_(140);
var invariant = _dereq_(144);
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
var Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function (markupList) {
!ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined;
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
!markupList[i] ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined;
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
var resultIndex;
for (resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ');
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags.
);
for (var j = 0; j < renderNodes.length; ++j) {
var renderNode = renderNodes[j];
if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
!!resultList.hasOwnProperty(resultIndex) ? "development" !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined;
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if ("development" !== 'production') {
console.error('Danger: Discarding unexpected node:', renderNode);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
!(resultListAssignmentCount === resultList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined;
!(resultList.length === markupList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined;
return resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) {
!ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
!markup ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined;
!(oldChild.tagName.toLowerCase() !== 'html') ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined;
var newChild;
if (typeof markup === 'string') {
newChild = createNodesFromMarkup(markup, emptyFunction)[0];
} else {
newChild = markup;
}
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
},{"130":130,"135":135,"136":136,"140":140,"144":144}],13:[function(_dereq_,module,exports){
/**
* 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 DefaultEventPluginOrder
*/
'use strict';
var keyOf = _dereq_(148);
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })];
module.exports = DefaultEventPluginOrder;
},{"148":148}],14:[function(_dereq_,module,exports){
/**
* 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 EnterLeaveEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(19);
var SyntheticMouseEvent = _dereq_(96);
var ReactMount = _dereq_(65);
var keyOf = _dereq_(148);
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactMount.getFirstReactDOM;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({ onMouseEnter: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
},
mouseLeave: {
registrationName: keyOf({ onMouseLeave: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
}
};
var extractedEvents = [null, null];
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (topLevelTarget.window === topLevelTarget) {
// `topLevelTarget` is probably a window object.
win = topLevelTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = topLevelTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
var fromID = '';
var toID = '';
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
fromID = topLevelTargetID;
to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement);
if (to) {
toID = ReactMount.getID(to);
} else {
to = win;
}
to = to || win;
} else {
from = win;
to = topLevelTarget;
toID = topLevelTargetID;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = from;
leave.relatedTarget = to;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = to;
enter.relatedTarget = from;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
extractedEvents[0] = leave;
extractedEvents[1] = enter;
return extractedEvents;
}
};
module.exports = EnterLeaveEventPlugin;
},{"148":148,"15":15,"19":19,"65":65,"96":96}],15:[function(_dereq_,module,exports){
/**
* 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 EventConstants
*/
'use strict';
var keyMirror = _dereq_(147);
var PropagationPhases = keyMirror({ bubbled: null, captured: null });
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topAbort: null,
topBlur: null,
topCanPlay: null,
topCanPlayThrough: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topDurationChange: null,
topEmptied: null,
topEncrypted: null,
topEnded: null,
topError: null,
topFocus: null,
topInput: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topLoadedData: null,
topLoadedMetadata: null,
topLoadStart: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topPause: null,
topPlay: null,
topPlaying: null,
topProgress: null,
topRateChange: null,
topReset: null,
topScroll: null,
topSeeked: null,
topSeeking: null,
topSelectionChange: null,
topStalled: null,
topSubmit: null,
topSuspend: null,
topTextInput: null,
topTimeUpdate: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topVolumeChange: null,
topWaiting: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
},{"147":147}],16:[function(_dereq_,module,exports){
/**
* 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 EventPluginHub
*/
'use strict';
var EventPluginRegistry = _dereq_(17);
var EventPluginUtils = _dereq_(18);
var ReactErrorUtils = _dereq_(56);
var accumulateInto = _dereq_(102);
var forEachAccumulated = _dereq_(110);
var invariant = _dereq_(144);
var warning = _dereq_(155);
/**
* Internal store for event listeners
*/
var listenerBank = {};
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @private
*/
var executeDispatchesAndRelease = function (event, simulated) {
if (event) {
EventPluginUtils.executeDispatchesInOrder(event, simulated);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
var executeDispatchesAndReleaseSimulated = function (e) {
return executeDispatchesAndRelease(e, true);
};
var executeDispatchesAndReleaseTopLevel = function (e) {
return executeDispatchesAndRelease(e, false);
};
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var InstanceHandle = null;
function validateInstanceHandle() {
var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave;
"development" !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined;
}
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {object} InjectedMount
* @public
*/
injectMount: EventPluginUtils.injection.injectMount,
/**
* @param {object} InjectedInstanceHandle
* @public
*/
injectInstanceHandle: function (InjectedInstanceHandle) {
InstanceHandle = InjectedInstanceHandle;
if ("development" !== 'production') {
validateInstanceHandle();
}
},
getInstanceHandle: function () {
if ("development" !== 'production') {
validateInstanceHandle();
}
return InstanceHandle;
},
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs,
registrationNameModules: EventPluginRegistry.registrationNameModules,
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {?function} listener The callback to store.
*/
putListener: function (id, registrationName, listener) {
!(typeof listener === 'function') ? "development" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined;
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.didPutListener) {
PluginModule.didPutListener(id, registrationName, listener);
}
},
/**
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function (id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes a listener from the registration bank.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function (id, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(id, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {string} id ID of the DOM element.
*/
deleteAllListeners: function (id) {
for (var registrationName in listenerBank) {
if (!listenerBank[registrationName][id]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(id, registrationName);
}
delete listenerBank[registrationName][id];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0; i < plugins.length; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
if (extractedEvents) {
events = accumulateInto(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function (events) {
if (events) {
eventQueue = accumulateInto(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function (simulated) {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
if (simulated) {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
} else {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
}
!!eventQueue ? "development" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined;
// This would be a good time to rethrow if any of the event handlers threw.
ReactErrorUtils.rethrowCaughtError();
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function () {
listenerBank = {};
},
__getListenerBank: function () {
return listenerBank;
}
};
module.exports = EventPluginHub;
},{"102":102,"110":110,"144":144,"155":155,"17":17,"18":18,"56":56}],17:[function(_dereq_,module,exports){
/**
* 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 EventPluginRegistry
* @typechecks static-only
*/
'use strict';
var invariant = _dereq_(144);
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
!(pluginIndex > -1) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined;
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
!PluginModule.extractEvents ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined;
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
!publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined;
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
!!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined;
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, PluginModule, eventName);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule, eventName) {
!!EventPluginRegistry.registrationNameModules[registrationName] ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined;
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies;
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function (InjectedEventPluginOrder) {
!!EventPluginOrder ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined;
// Clone the ordering so it cannot be dynamically mutated.
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function (injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var PluginModule = injectedNamesToPlugins[pluginName];
if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) {
!!namesToPlugins[pluginName] ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined;
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function (event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function () {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
}
};
module.exports = EventPluginRegistry;
},{"144":144}],18:[function(_dereq_,module,exports){
/**
* 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 EventPluginUtils
*/
'use strict';
var EventConstants = _dereq_(15);
var ReactErrorUtils = _dereq_(56);
var invariant = _dereq_(144);
var warning = _dereq_(155);
/**
* Injected dependencies:
*/
/**
* - `Mount`: [required] Module that can convert between React dom IDs and
* actual node references.
*/
var injection = {
Mount: null,
injectMount: function (InjectedMount) {
injection.Mount = InjectedMount;
if ("development" !== 'production') {
"development" !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined;
}
}
};
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if ("development" !== 'production') {
validateEventDispatches = function (event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
var listenersIsArr = Array.isArray(dispatchListeners);
var idsIsArr = Array.isArray(dispatchIDs);
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
"development" !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined;
};
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @param {function} listener Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, simulated, listener, domID) {
var type = event.type || 'unknown-event';
event.currentTarget = injection.Mount.getNode(domID);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID);
}
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("development" !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, simulated, dispatchListeners, dispatchIDs);
}
event._dispatchListeners = null;
event._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("development" !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchIDs = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if ("development" !== 'production') {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
!!Array.isArray(dispatchListener) ? "development" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined;
var res = dispatchListener ? dispatchListener(event, dispatchID) : null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getNode: function (id) {
return injection.Mount.getNode(id);
},
getID: function (node) {
return injection.Mount.getID(node);
},
injection: injection
};
module.exports = EventPluginUtils;
},{"144":144,"15":15,"155":155,"56":56}],19:[function(_dereq_,module,exports){
/**
* 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 EventPropagators
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(16);
var warning = _dereq_(155);
var accumulateInto = _dereq_(102);
var forEachAccumulated = _dereq_(110);
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, event) {
if ("development" !== 'production') {
"development" !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined;
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We cannot perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
},{"102":102,"110":110,"15":15,"155":155,"16":16}],20:[function(_dereq_,module,exports){
/**
* 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 FallbackCompositionState
* @typechecks static-only
*/
'use strict';
var PooledClass = _dereq_(24);
var assign = _dereq_(23);
var getTextContentAccessor = _dereq_(117);
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root;
this._startText = this.getText();
this._fallbackText = null;
}
assign(FallbackCompositionState.prototype, {
destructor: function () {
this._root = null;
this._startText = null;
this._fallbackText = null;
},
/**
* Get current text of input.
*
* @return {string}
*/
getText: function () {
if ('value' in this._root) {
return this._root.value;
}
return this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function () {
if (this._fallbackText) {
return this._fallbackText;
}
var start;
var startValue = this._startText;
var startLength = startValue.length;
var end;
var endValue = this.getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
this._fallbackText = endValue.slice(start, sliceTail);
return this._fallbackText;
}
});
PooledClass.addPoolingTo(FallbackCompositionState);
module.exports = FallbackCompositionState;
},{"117":117,"23":23,"24":24}],21:[function(_dereq_,module,exports){
/**
* 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 HTMLDOMPropertyConfig
*/
'use strict';
var DOMProperty = _dereq_(10);
var ExecutionEnvironment = _dereq_(130);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1');
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),
Properties: {
/**
* Standard Properties
*/
accept: null,
acceptCharset: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
challenge: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
classID: MUST_USE_ATTRIBUTE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
'default': HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formAction: MUST_USE_ATTRIBUTE,
formEncType: MUST_USE_ATTRIBUTE,
formMethod: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: MUST_USE_ATTRIBUTE,
frameBorder: MUST_USE_ATTRIBUTE,
headers: null,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
high: null,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
inputMode: MUST_USE_ATTRIBUTE,
integrity: null,
is: MUST_USE_ATTRIBUTE,
keyParams: MUST_USE_ATTRIBUTE,
keyType: MUST_USE_ATTRIBUTE,
kind: null,
label: null,
lang: null,
list: MUST_USE_ATTRIBUTE,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
low: null,
manifest: MUST_USE_ATTRIBUTE,
marginHeight: null,
marginWidth: null,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
minLength: MUST_USE_ATTRIBUTE,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
nonce: MUST_USE_ATTRIBUTE,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scoped: HAS_BOOLEAN_VALUE,
scrolling: null,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcLang: null,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
summary: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
wrap: null,
/**
* RDFa Properties
*/
about: MUST_USE_ATTRIBUTE,
datatype: MUST_USE_ATTRIBUTE,
inlist: MUST_USE_ATTRIBUTE,
prefix: MUST_USE_ATTRIBUTE,
// property is also supported for OpenGraph in meta tags.
property: MUST_USE_ATTRIBUTE,
resource: MUST_USE_ATTRIBUTE,
'typeof': MUST_USE_ATTRIBUTE,
vocab: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: MUST_USE_ATTRIBUTE,
autoCorrect: MUST_USE_ATTRIBUTE,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: null,
// color is for Safari mask-icon link
color: null,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: MUST_USE_ATTRIBUTE,
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
itemType: MUST_USE_ATTRIBUTE,
// itemID and itemRef are for Microdata support as well but
// only specified in the the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: MUST_USE_ATTRIBUTE,
itemRef: MUST_USE_ATTRIBUTE,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: null,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: MUST_USE_ATTRIBUTE,
// IE-only attribute that controls focus behavior
unselectable: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
autoSave: 'autosave',
// `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter.
// http://www.w3.org/TR/html5/forms.html#dom-fs-encoding
encType: 'encoding',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
},{"10":10,"130":130}],22:[function(_dereq_,module,exports){
/**
* 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 LinkedValueUtils
* @typechecks static-only
*/
'use strict';
var ReactPropTypes = _dereq_(74);
var ReactPropTypeLocations = _dereq_(73);
var invariant = _dereq_(144);
var warning = _dereq_(155);
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(inputProps) {
!(inputProps.checkedLink == null || inputProps.valueLink == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined;
}
function _assertValueLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.value == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined;
}
function _assertCheckedLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.checked == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined;
}
var propTypes = {
value: function (props, propName, componentName) {
if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
checked: function (props, propName, componentName) {
if (!props[propName] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
onChange: ReactPropTypes.func
};
var loggedTypeFailures = {};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
checkPropTypes: function (tagName, props, owner) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum(owner);
"development" !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined;
}
}
},
/**
* @param {object} inputProps Props for form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function (inputProps) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.value;
}
return inputProps.value;
},
/**
* @param {object} inputProps Props for form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function (inputProps) {
if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.value;
}
return inputProps.checked;
},
/**
* @param {object} inputProps Props for form component
* @param {SyntheticEvent} event change event to handle
*/
executeOnChange: function (inputProps, event) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.requestChange(event.target.value);
} else if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.requestChange(event.target.checked);
} else if (inputProps.onChange) {
return inputProps.onChange.call(undefined, event);
}
}
};
module.exports = LinkedValueUtils;
},{"144":144,"155":155,"73":73,"74":74}],23:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
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;
},{}],24:[function(_dereq_,module,exports){
/**
* 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 PooledClass
*/
'use strict';
var invariant = _dereq_(144);
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function (a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function (a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fourArgumentPooler = function (a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
var fiveArgumentPooler = function (a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function (instance) {
var Klass = this;
!(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{"144":144}],25:[function(_dereq_,module,exports){
/**
* 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 ReactBrowserComponentMixin
*/
'use strict';
var ReactInstanceMap = _dereq_(62);
var findDOMNode = _dereq_(108);
var warning = _dereq_(155);
var didWarnKey = '_getDOMNodeDidWarn';
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function () {
"development" !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined;
this.constructor[didWarnKey] = true;
return findDOMNode(this);
}
};
module.exports = ReactBrowserComponentMixin;
},{"108":108,"155":155,"62":62}],26:[function(_dereq_,module,exports){
/**
* 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 ReactBrowserEventEmitter
* @typechecks static-only
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(16);
var EventPluginRegistry = _dereq_(17);
var ReactEventEmitterMixin = _dereq_(57);
var ReactPerf = _dereq_(71);
var ViewportMetrics = _dereq_(101);
var assign = _dereq_(23);
var isEventSupported = _dereq_(119);
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topAbort: 'abort',
topBlur: 'blur',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topScroll: 'scroll',
topSeeked: 'seeked',
topSeeking: 'seeking',
topSelectionChange: 'selectionchange',
topStalled: 'stalled',
topSuspend: 'suspend',
topTextInput: 'textInput',
topTimeUpdate: 'timeupdate',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topVolumeChange: 'volumechange',
topWaiting: 'waiting',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function (ReactEventListener) {
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function (enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function () {
return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled());
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function (registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
if (dependency === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt);
}
} else if (dependency === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE);
}
} else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
}
// to make sure blur and focus event listeners are only attached once
isListening[topLevelTypes.topBlur] = true;
isListening[topLevelTypes.topFocus] = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
},
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function () {
if (!isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
},
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
registrationNameModules: EventPluginHub.registrationNameModules,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners
});
ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', {
putListener: 'putListener',
deleteListener: 'deleteListener'
});
module.exports = ReactBrowserEventEmitter;
},{"101":101,"119":119,"15":15,"16":16,"17":17,"23":23,"57":57,"71":71}],27:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildReconciler
* @typechecks static-only
*/
'use strict';
var ReactReconciler = _dereq_(76);
var instantiateReactComponent = _dereq_(118);
var shouldUpdateReactComponent = _dereq_(126);
var traverseAllChildren = _dereq_(127);
var warning = _dereq_(155);
function instantiateChild(childInstances, child, name) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child, null);
}
}
/**
* ReactChildReconciler provides helpers for initializing or updating a set of
* children. Its output is suitable for passing it onto ReactMultiChild which
* does diffed reordering and insertion.
*/
var ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function (nestedChildNodes, transaction, context) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
return childInstances;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextChildren Flat child element maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function (prevChildren, nextChildren, transaction, context) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
if (!nextChildren && !prevChildren) {
return null;
}
var name;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) {
ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context);
nextChildren[name] = prevChild;
} else {
if (prevChild) {
ReactReconciler.unmountComponent(prevChild, name);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement, null);
nextChildren[name] = nextChildInstance;
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
ReactReconciler.unmountComponent(prevChildren[name]);
}
}
return nextChildren;
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function (renderedChildren) {
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild);
}
}
}
};
module.exports = ReactChildReconciler;
},{"118":118,"126":126,"127":127,"155":155,"76":76}],28:[function(_dereq_,module,exports){
/**
* 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 ReactChildren
*/
'use strict';
var PooledClass = _dereq_(24);
var ReactElement = _dereq_(52);
var emptyFunction = _dereq_(136);
var traverseAllChildren = _dereq_(127);
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var fourArgumentPooler = PooledClass.fourArgumentPooler;
var userProvidedKeyEscapeRegex = /\/(?!\/)/g;
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, '//');
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
ForEachBookKeeping.prototype.destructor = function () {
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func;
var context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
MapBookKeeping.prototype.destructor = function () {
this.result = null;
this.keyPrefix = null;
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result;
var keyPrefix = bookKeeping.keyPrefix;
var func = bookKeeping.func;
var context = bookKeeping.context;
var mappedChild = func.call(context, child, bookKeeping.count++);
if (Array.isArray(mappedChild)) {
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
} else if (mappedChild != null) {
if (ReactElement.isValidElement(mappedChild)) {
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey);
}
result.push(mappedChild);
}
}
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
var escapedPrefix = '';
if (prefix != null) {
escapedPrefix = escapeUserProvidedKey(prefix) + '/';
}
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
}
/**
* Maps children that are typically specified as `props.children`.
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
function forEachSingleChildDummy(traverseContext, child, name) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*/
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
count: countChildren,
toArray: toArray
};
module.exports = ReactChildren;
},{"127":127,"136":136,"24":24,"52":52}],29:[function(_dereq_,module,exports){
/**
* 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 ReactClass
*/
'use strict';
var ReactComponent = _dereq_(30);
var ReactElement = _dereq_(52);
var ReactPropTypeLocations = _dereq_(73);
var ReactPropTypeLocationNames = _dereq_(72);
var ReactNoopUpdateQueue = _dereq_(69);
var assign = _dereq_(23);
var emptyObject = _dereq_(137);
var invariant = _dereq_(144);
var keyMirror = _dereq_(147);
var keyOf = _dereq_(148);
var warning = _dereq_(155);
var MIXINS_KEY = keyOf({ mixins: null });
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
var warnedSetProps = false;
function warnSetProps() {
if (!warnedSetProps) {
warnedSetProps = true;
"development" !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined;
}
}
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function (Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function (Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function (Constructor, childContextTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext);
}
Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function (Constructor, contextTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context);
}
Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function (Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function (Constructor, propTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop);
}
Constructor.propTypes = assign({}, Constructor.propTypes, propTypes);
},
statics: function (Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function () {} };
// noop
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an invariant so components
// don't show up in prod but not in __DEV__
"development" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined;
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.OVERRIDE_BASE) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined;
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined;
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
!(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
!!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
var proto = Constructor.prototype;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("development" !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = (name in RESERVED_SPEC_KEYS);
!!isReserved ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined;
var isInherited = (name in Constructor);
!!isInherited ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined;
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
!(one && two && typeof one === 'object' && typeof two === 'object') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined;
for (var key in two) {
if (two.hasOwnProperty(key)) {
!(one[key] === undefined) ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined;
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if ("development" !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
/* eslint-disable block-scoped-var, no-undef */
boundMethod.bind = function (newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
"development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined;
} else if (!args.length) {
"development" !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
/* eslint-enable */
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
for (var autoBindKey in component.__reactAutoBindMap) {
if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
var method = component.__reactAutoBindMap[autoBindKey];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
}
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function (newState, callback) {
this.updater.enqueueReplaceState(this, newState);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function () {
return this.updater.isMounted(this);
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
setProps: function (partialProps, callback) {
if ("development" !== 'production') {
warnSetProps();
}
this.updater.enqueueSetProps(this, partialProps);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
},
/**
* Replace all the props.
*
* @param {object} newProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
replaceProps: function (newProps, callback) {
if ("development" !== 'production') {
warnSetProps();
}
this.updater.enqueueReplaceProps(this, newProps);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
}
};
var ReactClassComponent = function () {};
assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function (spec) {
var Constructor = function (props, context, updater) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("development" !== 'production') {
"development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined;
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("development" !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined;
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if ("development" !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
!Constructor.prototype.render ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined;
"development" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined;
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
},
injection: {
injectMixin: function (mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactClass;
},{"137":137,"144":144,"147":147,"148":148,"155":155,"23":23,"30":30,"52":52,"69":69,"72":72,"73":73}],30:[function(_dereq_,module,exports){
/**
* 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 ReactComponent
*/
'use strict';
var ReactNoopUpdateQueue = _dereq_(69);
var canDefineProperty = _dereq_(104);
var emptyObject = _dereq_(137);
var invariant = _dereq_(144);
var warning = _dereq_(155);
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
ReactComponent.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined;
}
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if ("development" !== 'production') {
var deprecatedAPIs = {
getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'],
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceProps: ['replaceProps', 'Instead, call render again at the top level.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'],
setProps: ['setProps', 'Instead, call render again at the top level.']
};
var defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
"development" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined;
return undefined;
}
});
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
module.exports = ReactComponent;
},{"104":104,"137":137,"144":144,"155":155,"69":69}],31:[function(_dereq_,module,exports){
/**
* 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 ReactComponentBrowserEnvironment
*/
'use strict';
var ReactDOMIDOperations = _dereq_(40);
var ReactMount = _dereq_(65);
/**
* Abstracts away all functionality of the reconciler that requires knowledge of
* the browser context. TODO: These callers should be refactored to avoid the
* need for this injection.
*/
var ReactComponentBrowserEnvironment = {
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function (rootNodeID) {
ReactMount.purgeID(rootNodeID);
}
};
module.exports = ReactComponentBrowserEnvironment;
},{"40":40,"65":65}],32:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentEnvironment
*/
'use strict';
var invariant = _dereq_(144);
var injected = false;
var ReactComponentEnvironment = {
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*/
unmountIDFromEnvironment: null,
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkupByID: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function (environment) {
!!injected ? "development" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined;
ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment;
ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID;
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
},{"144":144}],33:[function(_dereq_,module,exports){
/**
* 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 ReactCompositeComponent
*/
'use strict';
var ReactComponentEnvironment = _dereq_(32);
var ReactCurrentOwner = _dereq_(34);
var ReactElement = _dereq_(52);
var ReactInstanceMap = _dereq_(62);
var ReactPerf = _dereq_(71);
var ReactPropTypeLocations = _dereq_(73);
var ReactPropTypeLocationNames = _dereq_(72);
var ReactReconciler = _dereq_(76);
var ReactUpdateQueue = _dereq_(82);
var assign = _dereq_(23);
var emptyObject = _dereq_(137);
var invariant = _dereq_(144);
var shouldUpdateReactComponent = _dereq_(126);
var warning = _dereq_(155);
function getDeclarationErrorAddendum(component) {
var owner = component._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
return Component(this.props, this.context, this.updater);
};
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function (element) {
this._currentElement = element;
this._rootNodeID = null;
this._instance = null;
// See ReactUpdateQueue
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (rootID, transaction, context) {
this._context = context;
this._mountOrder = nextMountID++;
this._rootNodeID = rootID;
var publicProps = this._processProps(this._currentElement.props);
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
// Initialize the public class
var inst;
var renderedElement;
// This is a way to detect if Component is a stateless arrow function
// component, which is not newable. It might not be 100% reliable but is
// something we can do until we start detecting that Component extends
// React.Component. We already assume that typeof Component === 'function'.
var canInstantiate = ('prototype' in Component);
if (canInstantiate) {
if ("development" !== 'production') {
ReactCurrentOwner.current = this;
try {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
}
}
if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) {
renderedElement = inst;
inst = new StatelessComponent(Component);
}
if ("development" !== 'production') {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
"development" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined;
} else {
// We support ES6 inheriting from React.Component, the module pattern,
// and stateless components, but not ES6 classes that don't extend
"development" !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined;
}
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = ReactUpdateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if ("development" !== 'production') {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
"development" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined;
"development" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined;
"development" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined;
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
if (inst.componentWillMount) {
inst.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
this._renderedComponent = this._instantiateReactComponent(renderedElement);
var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context));
if (inst.componentDidMount) {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function () {
var inst = this._instance;
if (inst.componentWillUnmount) {
inst.componentWillUnmount();
}
ReactReconciler.unmountComponent(this._renderedComponent);
this._renderedComponent = null;
this._instance = null;
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = null;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function (context) {
var maskedContext = null;
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function (context) {
var maskedContext = this._maskContext(context);
if ("development" !== 'production') {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function (currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
var childContext = inst.getChildContext && inst.getChildContext();
if (childContext) {
!(typeof Component.childContextTypes === 'object') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
if ("development" !== 'production') {
this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext);
}
for (var name in childContext) {
!(name in Component.childContextTypes) ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined;
}
return assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function (newProps) {
if ("development" !== 'production') {
var Component = this._currentElement.type;
if (Component.propTypes) {
this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop);
}
}
return newProps;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function (propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.getName();
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// top-level render calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
if (location === ReactPropTypeLocations.prop) {
// Preface gives us something to blacklist in warning module
"development" !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined;
} else {
"development" !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined;
}
}
}
}
},
receiveComponent: function (nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context);
}
if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext);
var nextProps;
// Distinguish between a props update versus a simple state update
if (prevParentElement === nextParentElement) {
// Skip checking prop types again -- we don't read inst.props to avoid
// warning for DOM component props in this upgrade
nextProps = nextParentElement.props;
} else {
nextProps = this._processProps(nextParentElement.props);
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (inst.componentWillReceiveProps) {
inst.componentWillReceiveProps(nextProps, nextContext);
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if ("development" !== 'production') {
"development" !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined;
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var inst = this._instance;
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
var prevProps;
var prevState;
var prevContext;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
prevContext = inst.context;
}
if (inst.componentWillUpdate) {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function (transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
ReactReconciler.unmountComponent(prevComponentInstance);
this._renderedComponent = this._instantiateReactComponent(nextRenderedElement);
var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context));
this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
}
},
/**
* @protected
*/
_replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) {
ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
var renderedComponent = inst.render();
if ("development" !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedComponent = null;
}
}
return renderedComponent;
},
/**
* @private
*/
_renderValidatedComponent: function () {
var renderedComponent;
ReactCurrentOwner.current = this;
try {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
!(
// TODO: An `isValidNode` function would probably be more appropriate
renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? "development" !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
return renderedComponent;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function (ref, component) {
var inst = this.getPublicInstance();
!(inst != null) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined;
var publicComponentInstance = component.getPublicInstance();
if ("development" !== 'production') {
var componentName = component && component.getName ? component.getName() : 'a component';
"development" !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function (ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function () {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function () {
var inst = this._instance;
if (inst instanceof StatelessComponent) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent',
_renderValidatedComponent: '_renderValidatedComponent'
});
var ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
},{"126":126,"137":137,"144":144,"155":155,"23":23,"32":32,"34":34,"52":52,"62":62,"71":71,"72":72,"73":73,"76":76,"82":82}],34:[function(_dereq_,module,exports){
/**
* 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 ReactCurrentOwner
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],35:[function(_dereq_,module,exports){
/**
* 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 ReactDOM
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var ReactCurrentOwner = _dereq_(34);
var ReactDOMTextComponent = _dereq_(46);
var ReactDefaultInjection = _dereq_(49);
var ReactInstanceHandles = _dereq_(61);
var ReactMount = _dereq_(65);
var ReactPerf = _dereq_(71);
var ReactReconciler = _dereq_(76);
var ReactUpdates = _dereq_(83);
var ReactVersion = _dereq_(84);
var findDOMNode = _dereq_(108);
var renderSubtreeIntoContainer = _dereq_(123);
var warning = _dereq_(155);
ReactDefaultInjection.inject();
var render = ReactPerf.measure('React', 'render', ReactMount.render);
var React = {
findDOMNode: findDOMNode,
render: render,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
version: ReactVersion,
/* eslint-disable camelcase */
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
/* eslint-enable camelcase */
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
CurrentOwner: ReactCurrentOwner,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
Reconciler: ReactReconciler,
TextComponent: ReactDOMTextComponent
});
}
if ("development" !== 'production') {
var ExecutionEnvironment = _dereq_(130);
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools');
}
}
// If we're in IE8, check to see if we are in compatibility mode and provide
// information on preventing compatibility mode
var ieCompatibilityMode = document.documentMode && document.documentMode < 8;
"development" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined;
var expectedFeatures = [
// shims
Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim,
// shams
Object.create, Object.freeze];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills');
break;
}
}
}
}
module.exports = React;
},{"108":108,"123":123,"130":130,"155":155,"34":34,"46":46,"49":49,"61":61,"65":65,"71":71,"76":76,"83":83,"84":84}],36:[function(_dereq_,module,exports){
/**
* 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 ReactDOMButton
*/
'use strict';
var mouseListenerNames = {
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
};
/**
* Implements a <button> native component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = {
getNativeProps: function (inst, props, context) {
if (!props.disabled) {
return props;
}
// Copy the props, except the mouse listeners
var nativeProps = {};
for (var key in props) {
if (props.hasOwnProperty(key) && !mouseListenerNames[key]) {
nativeProps[key] = props[key];
}
}
return nativeProps;
}
};
module.exports = ReactDOMButton;
},{}],37:[function(_dereq_,module,exports){
/**
* 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 ReactDOMComponent
* @typechecks static-only
*/
/* global hasOwnProperty:true */
'use strict';
var AutoFocusUtils = _dereq_(2);
var CSSPropertyOperations = _dereq_(5);
var DOMProperty = _dereq_(10);
var DOMPropertyOperations = _dereq_(11);
var EventConstants = _dereq_(15);
var ReactBrowserEventEmitter = _dereq_(26);
var ReactComponentBrowserEnvironment = _dereq_(31);
var ReactDOMButton = _dereq_(36);
var ReactDOMInput = _dereq_(41);
var ReactDOMOption = _dereq_(42);
var ReactDOMSelect = _dereq_(43);
var ReactDOMTextarea = _dereq_(47);
var ReactMount = _dereq_(65);
var ReactMultiChild = _dereq_(66);
var ReactPerf = _dereq_(71);
var ReactUpdateQueue = _dereq_(82);
var assign = _dereq_(23);
var canDefineProperty = _dereq_(104);
var escapeTextContentForBrowser = _dereq_(107);
var invariant = _dereq_(144);
var isEventSupported = _dereq_(119);
var keyOf = _dereq_(148);
var setInnerHTML = _dereq_(124);
var setTextContent = _dereq_(125);
var shallowEqual = _dereq_(153);
var validateDOMNesting = _dereq_(128);
var warning = _dereq_(155);
var deleteListener = ReactBrowserEventEmitter.deleteListener;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = { 'string': true, 'number': true };
var CHILDREN = keyOf({ children: null });
var STYLE = keyOf({ style: null });
var HTML = keyOf({ __html: null });
var ELEMENT_NODE_TYPE = 1;
function getDeclarationErrorAddendum(internalInstance) {
if (internalInstance) {
var owner = internalInstance._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' This DOM node was rendered by `' + name + '`.';
}
}
}
return '';
}
var legacyPropsDescriptor;
if ("development" !== 'production') {
legacyPropsDescriptor = {
props: {
enumerable: false,
get: function () {
var component = this._reactInternalComponent;
"development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined;
return component._currentElement.props;
}
}
};
}
function legacyGetDOMNode() {
if ("development" !== 'production') {
var component = this._reactInternalComponent;
"development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined;
}
return this;
}
function legacyIsMounted() {
var component = this._reactInternalComponent;
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined;
}
return !!component;
}
function legacySetStateEtc() {
if ("development" !== 'production') {
var component = this._reactInternalComponent;
"development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined;
}
}
function legacySetProps(partialProps, callback) {
var component = this._reactInternalComponent;
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
}
if (!component) {
return;
}
ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
}
}
function legacyReplaceProps(partialProps, callback) {
var component = this._reactInternalComponent;
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
}
if (!component) {
return;
}
ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
}
}
function friendlyStringify(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return '[' + obj.map(friendlyStringify).join(', ') + ']';
} else {
var pairs = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
}
}
return '{' + pairs.join(', ') + '}';
}
} else if (typeof obj === 'string') {
return JSON.stringify(obj);
} else if (typeof obj === 'function') {
return '[function object]';
}
// Differs from JSON.stringify in that undefined becauses undefined and that
// inf and nan don't become null
return String(obj);
}
var styleMutationWarning = {};
function checkAndWarnForMutatedStyle(style1, style2, component) {
if (style1 == null || style2 == null) {
return;
}
if (shallowEqual(style1, style2)) {
return;
}
var componentName = component._tag;
var owner = component._currentElement._owner;
var ownerName;
if (owner) {
ownerName = owner.getName();
}
var hash = ownerName + '|' + componentName;
if (styleMutationWarning.hasOwnProperty(hash)) {
return;
}
styleMutationWarning[hash] = true;
"development" !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined;
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if ("development" !== 'production') {
if (voidElementTags[component._tag]) {
"development" !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined;
}
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? "development" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined;
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "development" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined;
}
if ("development" !== 'production') {
"development" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined;
"development" !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined;
}
!(props.style == null || typeof props.style === 'object') ? "development" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined;
}
function enqueuePutListener(id, registrationName, listener, transaction) {
if ("development" !== 'production') {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
"development" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined;
}
var container = ReactMount.findReactContainerForID(id);
if (container) {
var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container;
listenTo(registrationName, doc);
}
transaction.getReactMountReady().enqueue(putListener, {
id: id,
registrationName: registrationName,
listener: listener
});
}
function putListener() {
var listenerToPut = this;
ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener);
}
// There are so many media events, it makes sense to just
// maintain a list rather than create a `trapBubbledEvent` for each
var mediaEvents = {
topAbort: 'abort',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topSeeked: 'seeked',
topSeeking: 'seeking',
topStalled: 'stalled',
topSuspend: 'suspend',
topTimeUpdate: 'timeupdate',
topVolumeChange: 'volumechange',
topWaiting: 'waiting'
};
function trapBubbledEventsLocal() {
var inst = this;
// If a component renders to null or if another component fatals and causes
// the state of the tree to be corrupted, `node` here can be null.
!inst._rootNodeID ? "development" !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined;
var node = ReactMount.getNode(inst._rootNodeID);
!node ? "development" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined;
switch (inst._tag) {
case 'iframe':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'video':
case 'audio':
inst._wrapperState.listeners = [];
// create listener for each media event
for (var event in mediaEvents) {
if (mediaEvents.hasOwnProperty(event)) {
inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node));
}
}
break;
case 'img':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'form':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)];
break;
}
}
function mountReadyInputWrapper() {
ReactDOMInput.mountReadyWrapper(this);
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special cased tags.
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
};
// NOTE: menuitem's close tag should be omitted, but that causes problems.
var newlineEatingTags = {
'listing': true,
'pre': true,
'textarea': true
};
// For HTML, certain tags cannot have children. This has the same purpose as
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags = assign({
'menuitem': true
}, omittedCloseTags);
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
var hasOwnProperty = ({}).hasOwnProperty;
function validateDangerousTag(tag) {
if (!hasOwnProperty.call(validatedTagCache, tag)) {
!VALID_TAG_REGEX.test(tag) ? "development" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined;
validatedTagCache[tag] = true;
}
}
function processChildContextDev(context, inst) {
// Pass down our tag name to child components for validation purposes
context = assign({}, context);
var info = context[validateDOMNesting.ancestorInfoContextKey];
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst);
return context;
}
function isCustomComponent(tagName, props) {
return tagName.indexOf('-') >= 0 || props.is != null;
}
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag) {
validateDangerousTag(tag);
this._tag = tag.toLowerCase();
this._renderedChildren = null;
this._previousStyle = null;
this._previousStyleCopy = null;
this._rootNodeID = null;
this._wrapperState = null;
this._topLevelWrapper = null;
this._nodeWithLegacyProperties = null;
if ("development" !== 'production') {
this._unprocessedContextDev = null;
this._processedContextDev = null;
}
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
construct: function (element) {
this._currentElement = element;
},
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {string} rootID The root DOM ID for this node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function (rootID, transaction, context) {
this._rootNodeID = rootID;
var props = this._currentElement.props;
switch (this._tag) {
case 'iframe':
case 'img':
case 'form':
case 'video':
case 'audio':
this._wrapperState = {
listeners: null
};
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'button':
props = ReactDOMButton.getNativeProps(this, props, context);
break;
case 'input':
ReactDOMInput.mountWrapper(this, props, context);
props = ReactDOMInput.getNativeProps(this, props, context);
break;
case 'option':
ReactDOMOption.mountWrapper(this, props, context);
props = ReactDOMOption.getNativeProps(this, props, context);
break;
case 'select':
ReactDOMSelect.mountWrapper(this, props, context);
props = ReactDOMSelect.getNativeProps(this, props, context);
context = ReactDOMSelect.processChildContext(this, props, context);
break;
case 'textarea':
ReactDOMTextarea.mountWrapper(this, props, context);
props = ReactDOMTextarea.getNativeProps(this, props, context);
break;
}
assertValidProps(this, props);
if ("development" !== 'production') {
if (context[validateDOMNesting.ancestorInfoContextKey]) {
validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]);
}
}
if ("development" !== 'production') {
this._unprocessedContextDev = context;
this._processedContextDev = processChildContextDev(context, this);
context = this._processedContextDev;
}
var mountImage;
if (transaction.useCreateElement) {
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
var el = ownerDocument.createElement(this._currentElement.type);
DOMPropertyOperations.setAttributeForID(el, this._rootNodeID);
// Populate node cache
ReactMount.getID(el);
this._updateDOMProperties({}, props, transaction, el);
this._createInitialChildren(transaction, props, context, el);
mountImage = el;
} else {
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
var tagContent = this._createContentMarkup(transaction, props, context);
if (!tagContent && omittedCloseTags[this._tag]) {
mountImage = tagOpen + '/>';
} else {
mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>';
}
}
switch (this._tag) {
case 'input':
transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this);
// falls through
case 'button':
case 'select':
case 'textarea':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
}
return mountImage;
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function (transaction, props) {
var ret = '<' + this._currentElement.type;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
if (propValue) {
enqueuePutListener(this._rootNodeID, propKey, propValue, transaction);
}
} else {
if (propKey === STYLE) {
if (propValue) {
if ("development" !== 'production') {
// See `_updateDOMProperties`. style block
this._previousStyle = propValue;
}
propValue = this._previousStyleCopy = assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var markup = null;
if (this._tag != null && isCustomComponent(this._tag, props)) {
if (propKey !== CHILDREN) {
markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret;
}
var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID);
return ret + ' ' + markupForID;
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function (transaction, props, context) {
var ret = '';
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
ret = innerHTML.__html;
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
ret = escapeTextContentForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
ret = mountImages.join('');
}
}
if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
return '\n' + ret;
} else {
return ret;
}
},
_createInitialChildren: function (transaction, props, context, el) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
setInnerHTML(el, innerHTML.__html);
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
setTextContent(el, contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
for (var i = 0; i < mountImages.length; i++) {
el.appendChild(mountImages[i]);
}
}
}
},
/**
* Receives a next element and updates the component.
*
* @internal
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
*/
receiveComponent: function (nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'button':
lastProps = ReactDOMButton.getNativeProps(this, lastProps);
nextProps = ReactDOMButton.getNativeProps(this, nextProps);
break;
case 'input':
ReactDOMInput.updateWrapper(this);
lastProps = ReactDOMInput.getNativeProps(this, lastProps);
nextProps = ReactDOMInput.getNativeProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getNativeProps(this, lastProps);
nextProps = ReactDOMOption.getNativeProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getNativeProps(this, lastProps);
nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
lastProps = ReactDOMTextarea.getNativeProps(this, lastProps);
nextProps = ReactDOMTextarea.getNativeProps(this, nextProps);
break;
}
if ("development" !== 'production') {
// If the context is reference-equal to the old one, pass down the same
// processed object so the update bailout in ReactReconciler behaves
// correctly (and identically in dev and prod). See #5005.
if (this._unprocessedContextDev !== context) {
this._unprocessedContextDev = context;
this._processedContextDev = processChildContextDev(context, this);
}
context = this._processedContextDev;
}
assertValidProps(this, nextProps);
this._updateDOMProperties(lastProps, nextProps, transaction, null);
this._updateDOMChildren(lastProps, nextProps, transaction, context);
if (!canDefineProperty && this._nodeWithLegacyProperties) {
this._nodeWithLegacyProperties.props = nextProps;
}
if (this._tag === 'select') {
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
}
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {?DOMElement} node
*/
_updateDOMProperties: function (lastProps, nextProps, transaction, node) {
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
this._previousStyleCopy = null;
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (lastProps[propKey]) {
// Only call deleteListener if there was a listener previously or
// else willDeleteListener gets called when there wasn't actually a
// listener (e.g., onClick={null})
deleteListener(this._rootNodeID, propKey);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
if ("development" !== 'production') {
checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this);
this._previousStyle = nextProp;
}
nextProp = this._previousStyleCopy = assign({}, nextProp);
} else {
this._previousStyleCopy = null;
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (nextProp) {
enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction);
} else if (lastProp) {
deleteListener(this._rootNodeID, propKey);
}
} else if (isCustomComponent(this._tag, nextProps)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
if (propKey === CHILDREN) {
nextProp = null;
}
DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp);
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (nextProp != null) {
DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
} else {
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
}
if (styleUpdates) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
CSSPropertyOperations.setValueForStyles(node, styleUpdates);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {object} context
*/
_updateDOMChildren: function (lastProps, nextProps, transaction, context) {
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html;
var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction, context);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
this.updateMarkup('' + nextHtml);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction, context);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function () {
switch (this._tag) {
case 'iframe':
case 'img':
case 'form':
case 'video':
case 'audio':
var listeners = this._wrapperState.listeners;
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].remove();
}
}
break;
case 'input':
ReactDOMInput.unmountWrapper(this);
break;
case 'html':
case 'head':
case 'body':
/**
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*/
!false ? "development" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined;
break;
}
this.unmountChildren();
ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._wrapperState = null;
if (this._nodeWithLegacyProperties) {
var node = this._nodeWithLegacyProperties;
node._reactInternalComponent = null;
this._nodeWithLegacyProperties = null;
}
},
getPublicInstance: function () {
if (!this._nodeWithLegacyProperties) {
var node = ReactMount.getNode(this._rootNodeID);
node._reactInternalComponent = this;
node.getDOMNode = legacyGetDOMNode;
node.isMounted = legacyIsMounted;
node.setState = legacySetStateEtc;
node.replaceState = legacySetStateEtc;
node.forceUpdate = legacySetStateEtc;
node.setProps = legacySetProps;
node.replaceProps = legacyReplaceProps;
if ("development" !== 'production') {
if (canDefineProperty) {
Object.defineProperties(node, legacyPropsDescriptor);
} else {
// updateComponent will update this property on subsequent renders
node.props = this._currentElement.props;
}
} else {
// updateComponent will update this property on subsequent renders
node.props = this._currentElement.props;
}
this._nodeWithLegacyProperties = node;
}
return this._nodeWithLegacyProperties;
}
};
ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent'
});
assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
},{"10":10,"104":104,"107":107,"11":11,"119":119,"124":124,"125":125,"128":128,"144":144,"148":148,"15":15,"153":153,"155":155,"2":2,"23":23,"26":26,"31":31,"36":36,"41":41,"42":42,"43":43,"47":47,"5":5,"65":65,"66":66,"71":71,"82":82}],38:[function(_dereq_,module,exports){
/**
* 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 ReactDOMFactories
* @typechecks static-only
*/
'use strict';
var ReactElement = _dereq_(52);
var ReactElementValidator = _dereq_(53);
var mapObject = _dereq_(149);
/**
* Create a factory that creates HTML tag elements.
*
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMFactory(tag) {
if ("development" !== 'production') {
return ReactElementValidator.createFactory(tag);
}
return ReactElement.createFactory(tag);
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOMFactories = mapObject({
a: 'a',
abbr: 'abbr',
address: 'address',
area: 'area',
article: 'article',
aside: 'aside',
audio: 'audio',
b: 'b',
base: 'base',
bdi: 'bdi',
bdo: 'bdo',
big: 'big',
blockquote: 'blockquote',
body: 'body',
br: 'br',
button: 'button',
canvas: 'canvas',
caption: 'caption',
cite: 'cite',
code: 'code',
col: 'col',
colgroup: 'colgroup',
data: 'data',
datalist: 'datalist',
dd: 'dd',
del: 'del',
details: 'details',
dfn: 'dfn',
dialog: 'dialog',
div: 'div',
dl: 'dl',
dt: 'dt',
em: 'em',
embed: 'embed',
fieldset: 'fieldset',
figcaption: 'figcaption',
figure: 'figure',
footer: 'footer',
form: 'form',
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
head: 'head',
header: 'header',
hgroup: 'hgroup',
hr: 'hr',
html: 'html',
i: 'i',
iframe: 'iframe',
img: 'img',
input: 'input',
ins: 'ins',
kbd: 'kbd',
keygen: 'keygen',
label: 'label',
legend: 'legend',
li: 'li',
link: 'link',
main: 'main',
map: 'map',
mark: 'mark',
menu: 'menu',
menuitem: 'menuitem',
meta: 'meta',
meter: 'meter',
nav: 'nav',
noscript: 'noscript',
object: 'object',
ol: 'ol',
optgroup: 'optgroup',
option: 'option',
output: 'output',
p: 'p',
param: 'param',
picture: 'picture',
pre: 'pre',
progress: 'progress',
q: 'q',
rp: 'rp',
rt: 'rt',
ruby: 'ruby',
s: 's',
samp: 'samp',
script: 'script',
section: 'section',
select: 'select',
small: 'small',
source: 'source',
span: 'span',
strong: 'strong',
style: 'style',
sub: 'sub',
summary: 'summary',
sup: 'sup',
table: 'table',
tbody: 'tbody',
td: 'td',
textarea: 'textarea',
tfoot: 'tfoot',
th: 'th',
thead: 'thead',
time: 'time',
title: 'title',
tr: 'tr',
track: 'track',
u: 'u',
ul: 'ul',
'var': 'var',
video: 'video',
wbr: 'wbr',
// SVG
circle: 'circle',
clipPath: 'clipPath',
defs: 'defs',
ellipse: 'ellipse',
g: 'g',
image: 'image',
line: 'line',
linearGradient: 'linearGradient',
mask: 'mask',
path: 'path',
pattern: 'pattern',
polygon: 'polygon',
polyline: 'polyline',
radialGradient: 'radialGradient',
rect: 'rect',
stop: 'stop',
svg: 'svg',
text: 'text',
tspan: 'tspan'
}, createDOMFactory);
module.exports = ReactDOMFactories;
},{"149":149,"52":52,"53":53}],39:[function(_dereq_,module,exports){
/**
* 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 ReactDOMFeatureFlags
*/
'use strict';
var ReactDOMFeatureFlags = {
useCreateElement: false
};
module.exports = ReactDOMFeatureFlags;
},{}],40:[function(_dereq_,module,exports){
/**
* 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 ReactDOMIDOperations
* @typechecks static-only
*/
'use strict';
var DOMChildrenOperations = _dereq_(9);
var DOMPropertyOperations = _dereq_(11);
var ReactMount = _dereq_(65);
var ReactPerf = _dereq_(71);
var invariant = _dereq_(144);
/**
* Errors for properties that should not be updated with `updatePropertyByID()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* Operations used to process updates to DOM nodes.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function (id, name, value) {
var node = ReactMount.getNode(id);
!!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? "development" !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined;
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function (id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
},
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: function (updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
};
ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', {
dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID',
dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates'
});
module.exports = ReactDOMIDOperations;
},{"11":11,"144":144,"65":65,"71":71,"9":9}],41:[function(_dereq_,module,exports){
/**
* 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 ReactDOMInput
*/
'use strict';
var ReactDOMIDOperations = _dereq_(40);
var LinkedValueUtils = _dereq_(22);
var ReactMount = _dereq_(65);
var ReactUpdates = _dereq_(83);
var assign = _dereq_(23);
var invariant = _dereq_(144);
var instancesByReactID = {};
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
}
/**
* Implements an <input> native component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = {
getNativeProps: function (inst, props, context) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var nativeProps = assign({}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if ("development" !== 'production') {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.defaultChecked || false,
initialValue: defaultValue != null ? defaultValue : null,
onChange: _handleChange.bind(inst)
};
},
mountReadyWrapper: function (inst) {
// Can't be in mountWrapper or else server rendering leaks.
instancesByReactID[inst._rootNodeID] = inst;
},
unmountWrapper: function (inst) {
delete instancesByReactID[inst._rootNodeID];
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
if (checked != null) {
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false);
}
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactMount.getNode(this._rootNodeID);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React with non-React.
var otherID = ReactMount.getID(otherNode);
!otherID ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined;
var otherInstance = instancesByReactID[otherID];
!otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined;
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
module.exports = ReactDOMInput;
},{"144":144,"22":22,"23":23,"40":40,"65":65,"83":83}],42:[function(_dereq_,module,exports){
/**
* 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 ReactDOMOption
*/
'use strict';
var ReactChildren = _dereq_(28);
var ReactDOMSelect = _dereq_(43);
var assign = _dereq_(23);
var warning = _dereq_(155);
var valueContextKey = ReactDOMSelect.valueContextKey;
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = {
mountWrapper: function (inst, props, context) {
// TODO (yungsters): Remove support for `selected` in <option>.
if ("development" !== 'production') {
"development" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined;
}
// Look up whether this option is 'selected' via context
var selectValue = context[valueContextKey];
// If context key is null (e.g., no specified value or after initial mount)
// or missing (e.g., for <datalist>), we don't change props.selected
var selected = null;
if (selectValue != null) {
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) {
if ('' + selectValue[i] === '' + props.value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === '' + props.value;
}
}
inst._wrapperState = { selected: selected };
},
getNativeProps: function (inst, props, context) {
var nativeProps = assign({ selected: undefined, children: undefined }, props);
// Read state only from initial mount because <select> updates value
// manually; we need the initial state only for server rendering
if (inst._wrapperState.selected != null) {
nativeProps.selected = inst._wrapperState.selected;
}
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
ReactChildren.forEach(props.children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else {
"development" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined;
}
});
if (content) {
nativeProps.children = content;
}
return nativeProps;
}
};
module.exports = ReactDOMOption;
},{"155":155,"23":23,"28":28,"43":43}],43:[function(_dereq_,module,exports){
/**
* 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 ReactDOMSelect
*/
'use strict';
var LinkedValueUtils = _dereq_(22);
var ReactMount = _dereq_(65);
var ReactUpdates = _dereq_(83);
var assign = _dereq_(23);
var warning = _dereq_(155);
var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2);
function updateOptionsIfPendingUpdateAndMounted() {
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
this._wrapperState.pendingUpdate = false;
var props = this._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
updateOptions(this, Boolean(props.multiple), value);
}
}
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
var valuePropNames = ['value', 'defaultValue'];
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function checkSelectPropTypes(inst, props) {
var owner = inst._currentElement._owner;
LinkedValueUtils.checkPropTypes('select', props, owner);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
if (props.multiple) {
"development" !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
} else {
"development" !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
}
}
}
/**
* @param {ReactDOMComponent} inst
* @param {boolean} multiple
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(inst, multiple, propValue) {
var selectedValue, i;
var options = ReactMount.getNode(inst._rootNodeID).options;
if (multiple) {
selectedValue = {};
for (i = 0; i < propValue.length; i++) {
selectedValue['' + propValue[i]] = true;
}
for (i = 0; i < options.length; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
if (options[i].selected !== selected) {
options[i].selected = selected;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
selectedValue = '' + propValue;
for (i = 0; i < options.length; i++) {
if (options[i].value === selectedValue) {
options[i].selected = true;
return;
}
}
if (options.length) {
options[0].selected = true;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = {
valueContextKey: valueContextKey,
getNativeProps: function (inst, props, context) {
return assign({}, props, {
onChange: inst._wrapperState.onChange,
value: undefined
});
},
mountWrapper: function (inst, props) {
if ("development" !== 'production') {
checkSelectPropTypes(inst, props);
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
pendingUpdate: false,
initialValue: value != null ? value : props.defaultValue,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
};
},
processChildContext: function (inst, props, context) {
// Pass down initial value so initial generated markup has correct
// `selected` attributes
var childContext = assign({}, context);
childContext[valueContextKey] = inst._wrapperState.initialValue;
return childContext;
},
postUpdateWrapper: function (inst) {
var props = inst._currentElement.props;
// After the initial mount, we control selected-ness manually so don't pass
// the context value down
inst._wrapperState.initialValue = undefined;
var wasMultiple = inst._wrapperState.wasMultiple;
inst._wrapperState.wasMultiple = Boolean(props.multiple);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
inst._wrapperState.pendingUpdate = false;
updateOptions(inst, Boolean(props.multiple), value);
} else if (wasMultiple !== Boolean(props.multiple)) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (props.defaultValue != null) {
updateOptions(inst, Boolean(props.multiple), props.defaultValue);
} else {
// Revert the select back to its default unselected state.
updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
}
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
this._wrapperState.pendingUpdate = true;
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
module.exports = ReactDOMSelect;
},{"155":155,"22":22,"23":23,"65":65,"83":83}],44:[function(_dereq_,module,exports){
/**
* 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 ReactDOMSelection
*/
'use strict';
var ExecutionEnvironment = _dereq_(130);
var getNodeForCharacterOffset = _dereq_(116);
var getTextContentAccessor = _dereq_(117);
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// In Firefox, range.startContainer and range.endContainer can be "anonymous
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
// divs do not seem to expose properties, triggering a "Permission denied
// error" if any of its properties are accessed. The only seemingly possible
// way to avoid erroring is to access a property that typically works for
// non-anonymous divs and catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
currentRange.startContainer.nodeType;
currentRange.endContainer.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (typeof offsets.end === 'undefined') {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window);
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
},{"116":116,"117":117,"130":130}],45:[function(_dereq_,module,exports){
/**
* 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 ReactDOMServer
*/
'use strict';
var ReactDefaultInjection = _dereq_(49);
var ReactServerRendering = _dereq_(80);
var ReactVersion = _dereq_(84);
ReactDefaultInjection.inject();
var ReactDOMServer = {
renderToString: ReactServerRendering.renderToString,
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
version: ReactVersion
};
module.exports = ReactDOMServer;
},{"49":49,"80":80,"84":84}],46:[function(_dereq_,module,exports){
/**
* 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 ReactDOMTextComponent
* @typechecks static-only
*/
'use strict';
var DOMChildrenOperations = _dereq_(9);
var DOMPropertyOperations = _dereq_(11);
var ReactComponentBrowserEnvironment = _dereq_(31);
var ReactMount = _dereq_(65);
var assign = _dereq_(23);
var escapeTextContentForBrowser = _dereq_(107);
var setTextContent = _dereq_(125);
var validateDOMNesting = _dereq_(128);
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings in elements so that they can undergo
* the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function (props) {
// This constructor and its argument is currently used by mocks.
};
assign(ReactDOMTextComponent.prototype, {
/**
* @param {ReactText} text
* @internal
*/
construct: function (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// Properties
this._rootNodeID = null;
this._mountIndex = 0;
},
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (rootID, transaction, context) {
if ("development" !== 'production') {
if (context[validateDOMNesting.ancestorInfoContextKey]) {
validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]);
}
}
this._rootNodeID = rootID;
if (transaction.useCreateElement) {
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
var el = ownerDocument.createElement('span');
DOMPropertyOperations.setAttributeForID(el, rootID);
// Populate node cache
ReactMount.getID(el);
setTextContent(el, this._stringText);
return el;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this in a `span` for the reasons stated above, but
// since this is a situation where React won't take over (static pages),
// we can simply return the text as it is.
return escapedText;
}
return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>';
}
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function (nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var node = ReactMount.getNode(this._rootNodeID);
DOMChildrenOperations.updateTextContent(node, nextStringText);
}
}
},
unmountComponent: function () {
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
}
});
module.exports = ReactDOMTextComponent;
},{"107":107,"11":11,"125":125,"128":128,"23":23,"31":31,"65":65,"9":9}],47:[function(_dereq_,module,exports){
/**
* 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 ReactDOMTextarea
*/
'use strict';
var LinkedValueUtils = _dereq_(22);
var ReactDOMIDOperations = _dereq_(40);
var ReactUpdates = _dereq_(83);
var assign = _dereq_(23);
var invariant = _dereq_(144);
var warning = _dereq_(155);
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
}
/**
* Implements a <textarea> native component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = {
getNativeProps: function (inst, props, context) {
!(props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
var nativeProps = assign({}, props, {
defaultValue: undefined,
value: undefined,
children: inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if ("development" !== 'production') {
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
}
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = props.children;
if (children != null) {
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined;
}
!(defaultValue == null) ? "development" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined;
if (Array.isArray(children)) {
!(children.length <= 1) ? "development" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined;
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: '' + (value != null ? value : defaultValue),
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
module.exports = ReactDOMTextarea;
},{"144":144,"155":155,"22":22,"23":23,"40":40,"83":83}],48:[function(_dereq_,module,exports){
/**
* 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 ReactDefaultBatchingStrategy
*/
'use strict';
var ReactUpdates = _dereq_(83);
var Transaction = _dereq_(100);
var assign = _dereq_(23);
var emptyFunction = _dereq_(136);
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function () {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d, e);
} else {
transaction.perform(callback, null, a, b, c, d, e);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"100":100,"136":136,"23":23,"83":83}],49:[function(_dereq_,module,exports){
/**
* 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 ReactDefaultInjection
*/
'use strict';
var BeforeInputEventPlugin = _dereq_(3);
var ChangeEventPlugin = _dereq_(7);
var ClientReactRootIndex = _dereq_(8);
var DefaultEventPluginOrder = _dereq_(13);
var EnterLeaveEventPlugin = _dereq_(14);
var ExecutionEnvironment = _dereq_(130);
var HTMLDOMPropertyConfig = _dereq_(21);
var ReactBrowserComponentMixin = _dereq_(25);
var ReactComponentBrowserEnvironment = _dereq_(31);
var ReactDefaultBatchingStrategy = _dereq_(48);
var ReactDOMComponent = _dereq_(37);
var ReactDOMTextComponent = _dereq_(46);
var ReactEventListener = _dereq_(58);
var ReactInjection = _dereq_(59);
var ReactInstanceHandles = _dereq_(61);
var ReactMount = _dereq_(65);
var ReactReconcileTransaction = _dereq_(75);
var SelectEventPlugin = _dereq_(86);
var ServerReactRootIndex = _dereq_(87);
var SimpleEventPlugin = _dereq_(88);
var SVGDOMPropertyConfig = _dereq_(85);
var alreadyInjected = false;
function inject() {
if (alreadyInjected) {
// TODO: This is currently true because these injections are shared between
// the client and the server package. They should be built independently
// and not share any injection state. Then this problem will be solved.
return;
}
alreadyInjected = true;
ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
ReactInjection.EventPluginHub.injectMount(ReactMount);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent);
ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent);
ReactInjection.Class.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if ("development" !== 'production') {
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
if (/[?&]react_perf\b/.test(url)) {
var ReactDefaultPerf = _dereq_(50);
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
},{"13":13,"130":130,"14":14,"21":21,"25":25,"3":3,"31":31,"37":37,"46":46,"48":48,"50":50,"58":58,"59":59,"61":61,"65":65,"7":7,"75":75,"8":8,"85":85,"86":86,"87":87,"88":88}],50:[function(_dereq_,module,exports){
/**
* 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 ReactDefaultPerf
* @typechecks static-only
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactDefaultPerfAnalysis = _dereq_(51);
var ReactMount = _dereq_(65);
var ReactPerf = _dereq_(71);
var performanceNow = _dereq_(152);
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
function addValue(obj, key, val) {
obj[key] = (obj[key] || 0) + val;
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_mountStack: [0],
_injected: false,
start: function () {
if (!ReactDefaultPerf._injected) {
ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure);
}
ReactDefaultPerf._allMeasurements.length = 0;
ReactPerf.enableMeasure = true;
},
stop: function () {
ReactPerf.enableMeasure = false;
},
getLastMeasurements: function () {
return ReactDefaultPerf._allMeasurements;
},
printExclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Component class name': item.componentName,
'Total inclusive time (ms)': roundFloat(item.inclusive),
'Exclusive mount time (ms)': roundFloat(item.exclusive),
'Exclusive render time (ms)': roundFloat(item.render),
'Mount time per instance (ms)': roundFloat(item.exclusive / item.count),
'Render time per instance (ms)': roundFloat(item.render / item.count),
'Instances': item.count
};
}));
// TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct
// number.
},
printInclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Inclusive time (ms)': roundFloat(item.time),
'Instances': item.count
};
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
getMeasurementsSummaryMap: function (measurements) {
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true);
return summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
});
},
printWasted: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
printDOM: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements);
console.table(summary.map(function (item) {
var result = {};
result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id;
result.type = item.type;
result.args = JSON.stringify(item.args);
return result;
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
_recordWrite: function (id, fnName, totalTime, args) {
// TODO: totalTime isn't that useful since it doesn't count paints/reflows
var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes;
writes[id] = writes[id] || [];
writes[id].push({
type: fnName,
time: totalTime,
args: args
});
},
measure: function (moduleName, fnName, func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var totalTime;
var rv;
var start;
if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') {
// A "measurement" is a set of metrics recorded for each flush. We want
// to group the metrics for a given flush together so we can look at the
// components that rendered and the DOM operations that actually
// happened to determine the amount of "wasted work" performed.
ReactDefaultPerf._allMeasurements.push({
exclusive: {},
inclusive: {},
render: {},
counts: {},
writes: {},
displayNames: {},
totalTime: 0,
created: {}
});
start = performanceNow();
rv = func.apply(this, args);
ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start;
return rv;
} else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') {
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (fnName === '_mountImageIntoNode') {
var mountID = ReactMount.getID(args[1]);
ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
// special format
args[0].forEach(function (update) {
var writeArgs = {};
if (update.fromIndex !== null) {
writeArgs.fromIndex = update.fromIndex;
}
if (update.toIndex !== null) {
writeArgs.toIndex = update.toIndex;
}
if (update.textContent !== null) {
writeArgs.textContent = update.textContent;
}
if (update.markupIndex !== null) {
writeArgs.markup = args[1][update.markupIndex];
}
ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs);
});
} else {
// basic format
var id = args[0];
if (typeof id === 'object') {
id = ReactMount.getID(args[0]);
}
ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1));
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
if (this._currentElement.type === ReactMount.TopLevelWrapper) {
return func.apply(this, args);
}
var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID;
var isRender = fnName === '_renderValidatedComponent';
var isMount = fnName === 'mountComponent';
var mountStack = ReactDefaultPerf._mountStack;
var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1];
if (isRender) {
addValue(entry.counts, rootNodeID, 1);
} else if (isMount) {
entry.created[rootNodeID] = true;
mountStack.push(0);
}
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (isRender) {
addValue(entry.render, rootNodeID, totalTime);
} else if (isMount) {
var subMountTime = mountStack.pop();
mountStack[mountStack.length - 1] += totalTime;
addValue(entry.exclusive, rootNodeID, totalTime - subMountTime);
addValue(entry.inclusive, rootNodeID, totalTime);
} else {
addValue(entry.inclusive, rootNodeID, totalTime);
}
entry.displayNames[rootNodeID] = {
current: this.getName(),
owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
},{"10":10,"152":152,"51":51,"65":65,"71":71}],51:[function(_dereq_,module,exports){
/**
* 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 ReactDefaultPerfAnalysis
*/
'use strict';
var assign = _dereq_(23);
// Don't try to save users less than 1.2ms (a number I made up)
var DONT_CARE_THRESHOLD = 1.2;
var DOM_OPERATION_TYPES = {
'_mountImageIntoNode': 'set innerHTML',
INSERT_MARKUP: 'set innerHTML',
MOVE_EXISTING: 'move',
REMOVE_NODE: 'remove',
SET_MARKUP: 'set innerHTML',
TEXT_CONTENT: 'set textContent',
'setValueForProperty': 'update attribute',
'setValueForAttribute': 'update attribute',
'deleteValueForProperty': 'remove attribute',
'setValueForStyles': 'update styles',
'replaceNodeWithMarkup': 'replace',
'updateTextContent': 'set textContent'
};
function getTotalTime(measurements) {
// TODO: return number of DOM ops? could be misleading.
// TODO: measure dropped frames after reconcile?
// TODO: log total time of each reconcile and the top-level component
// class that triggered it.
var totalTime = 0;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
totalTime += measurement.totalTime;
}
return totalTime;
}
function getDOMSummary(measurements) {
var items = [];
measurements.forEach(function (measurement) {
Object.keys(measurement.writes).forEach(function (id) {
measurement.writes[id].forEach(function (write) {
items.push({
id: id,
type: DOM_OPERATION_TYPES[write.type] || write.type,
args: write.args
});
});
});
});
return items;
}
function getExclusiveSummary(measurements) {
var candidates = {};
var displayName;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
displayName = measurement.displayNames[id].current;
candidates[displayName] = candidates[displayName] || {
componentName: displayName,
inclusive: 0,
exclusive: 0,
render: 0,
count: 0
};
if (measurement.render[id]) {
candidates[displayName].render += measurement.render[id];
}
if (measurement.exclusive[id]) {
candidates[displayName].exclusive += measurement.exclusive[id];
}
if (measurement.inclusive[id]) {
candidates[displayName].inclusive += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[displayName].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (displayName in candidates) {
if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) {
arr.push(candidates[displayName]);
}
}
arr.sort(function (a, b) {
return b.exclusive - a.exclusive;
});
return arr;
}
function getInclusiveSummary(measurements, onlyClean) {
var candidates = {};
var inclusiveKey;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
var cleanComponents;
if (onlyClean) {
cleanComponents = getUnchangedComponents(measurement);
}
for (var id in allIDs) {
if (onlyClean && !cleanComponents[id]) {
continue;
}
var displayName = measurement.displayNames[id];
// Inclusive time is not useful for many components without knowing where
// they are instantiated. So we aggregate inclusive time with both the
// owner and current displayName as the key.
inclusiveKey = displayName.owner + ' > ' + displayName.current;
candidates[inclusiveKey] = candidates[inclusiveKey] || {
componentName: inclusiveKey,
time: 0,
count: 0
};
if (measurement.inclusive[id]) {
candidates[inclusiveKey].time += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[inclusiveKey].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (inclusiveKey in candidates) {
if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) {
arr.push(candidates[inclusiveKey]);
}
}
arr.sort(function (a, b) {
return b.time - a.time;
});
return arr;
}
function getUnchangedComponents(measurement) {
// For a given reconcile, look at which components did not actually
// render anything to the DOM and return a mapping of their ID to
// the amount of time it took to render the entire subtree.
var cleanComponents = {};
var dirtyLeafIDs = Object.keys(measurement.writes);
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggered
// a DOM op is in its subtree.
for (var i = 0; i < dirtyLeafIDs.length; i++) {
if (dirtyLeafIDs[i].indexOf(id) === 0) {
isDirty = true;
break;
}
}
// check if component newly created
if (measurement.created[id]) {
isDirty = true;
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
},{"23":23}],52:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElement
*/
'use strict';
var ReactCurrentOwner = _dereq_(34);
var assign = _dereq_(23);
var canDefineProperty = _dereq_(104);
// The Symbol used to tag the ReactElement type. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
/**
* 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 {*} key
* @param {string|object} ref
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @param {*} owner
* @param {*} props
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if ("development" !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
Object.freeze(element.props);
Object.freeze(element);
}
return element;
};
ReactElement.createElement = function (type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
ReactElement.createFactory = function (type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
};
ReactElement.cloneAndReplaceProps = function (oldElement, newProps) {
var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps);
if ("development" !== 'production') {
// If the key on the original is valid, then the clone is valid
newElement._store.validated = oldElement._store.validated;
}
return newElement;
};
ReactElement.cloneElement = function (element, config, children) {
var propName;
// Original props are copied
var props = assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Self is preserved since the owner is preserved.
var self = element._self;
// Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (config.ref !== undefined) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (config.key !== undefined) {
key = '' + config.key;
}
// Remaining properties override existing props
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;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
};
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
module.exports = ReactElement;
},{"104":104,"23":23,"34":34}],53:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactElement = _dereq_(52);
var ReactPropTypeLocations = _dereq_(73);
var ReactPropTypeLocationNames = _dereq_(72);
var ReactCurrentOwner = _dereq_(34);
var canDefineProperty = _dereq_(104);
var getIteratorFn = _dereq_(115);
var invariant = _dereq_(144);
var warning = _dereq_(155);
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
var loggedTypeFailures = {};
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var addenda = getAddendaForKeyUse('uniqueKey', element, parentType);
if (addenda === null) {
// we already showed the warning
return;
}
"development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined;
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} messageType A key used for de-duping warnings.
* @param {ReactElement} element Component that requires a key.
* @param {*} parentType element's parent's type.
* @returns {?object} A set of addenda to use in the warning message, or null
* if the warning has already been shown before (and shouldn't be shown again).
*/
function getAddendaForKeyUse(messageType, element, parentType) {
var addendum = getDeclarationErrorAddendum();
if (!addendum) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
addendum = ' Check the top-level render call using <' + parentName + '>.';
}
}
var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {});
if (memoizer[addendum]) {
return null;
}
memoizer[addendum] = true;
var addenda = {
parentOrOwner: addendum,
url: ' See https://fb.me/react-warning-keys for more information.',
childOwner: null
};
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
return addenda;
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Assert that the props are valid
*
* @param {string} componentName Name of the component for error messages.
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
"development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum();
"development" !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined;
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
var componentClass = element.type;
if (typeof componentClass !== 'function') {
return;
}
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop);
}
if (typeof componentClass.getDefaultProps === 'function') {
"development" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined;
}
}
var ReactElementValidator = {
createElement: function (type, props, children) {
var validType = typeof type === 'string' || typeof type === 'function';
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
"development" !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined;
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
validatePropTypes(element);
return element;
},
createFactory: function (type) {
var validatedFactory = ReactElementValidator.createElement.bind(null, type);
// Legacy hook TODO: Warn if this is accessed
validatedFactory.type = type;
if ("development" !== 'production') {
if (canDefineProperty) {
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
"development" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined;
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
}
return validatedFactory;
},
cloneElement: function (element, props, children) {
var newElement = ReactElement.cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
};
module.exports = ReactElementValidator;
},{"104":104,"115":115,"144":144,"155":155,"34":34,"52":52,"72":72,"73":73}],54:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponent
*/
'use strict';
var ReactElement = _dereq_(52);
var ReactEmptyComponentRegistry = _dereq_(55);
var ReactReconciler = _dereq_(76);
var assign = _dereq_(23);
var placeholderElement;
var ReactEmptyComponentInjection = {
injectEmptyComponent: function (component) {
placeholderElement = ReactElement.createElement(component);
}
};
var ReactEmptyComponent = function (instantiate) {
this._currentElement = null;
this._rootNodeID = null;
this._renderedComponent = instantiate(placeholderElement);
};
assign(ReactEmptyComponent.prototype, {
construct: function (element) {},
mountComponent: function (rootID, transaction, context) {
ReactEmptyComponentRegistry.registerNullComponentID(rootID);
this._rootNodeID = rootID;
return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context);
},
receiveComponent: function () {},
unmountComponent: function (rootID, transaction, context) {
ReactReconciler.unmountComponent(this._renderedComponent);
ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID);
this._rootNodeID = null;
this._renderedComponent = null;
}
});
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
},{"23":23,"52":52,"55":55,"76":76}],55:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponentRegistry
*/
'use strict';
// This registry keeps track of the React IDs of the components that rendered to
// `null` (in reality a placeholder such as `noscript`)
var nullComponentIDsRegistry = {};
/**
* @param {string} id Component's `_rootNodeID`.
* @return {boolean} True if the component is rendered to null.
*/
function isNullComponentID(id) {
return !!nullComponentIDsRegistry[id];
}
/**
* Mark the component as having rendered to null.
* @param {string} id Component's `_rootNodeID`.
*/
function registerNullComponentID(id) {
nullComponentIDsRegistry[id] = true;
}
/**
* Unmark the component as having rendered to null: it renders to something now.
* @param {string} id Component's `_rootNodeID`.
*/
function deregisterNullComponentID(id) {
delete nullComponentIDsRegistry[id];
}
var ReactEmptyComponentRegistry = {
isNullComponentID: isNullComponentID,
registerNullComponentID: registerNullComponentID,
deregisterNullComponentID: deregisterNullComponentID
};
module.exports = ReactEmptyComponentRegistry;
},{}],56:[function(_dereq_,module,exports){
/**
* 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 ReactErrorUtils
* @typechecks
*/
'use strict';
var caughtError = null;
/**
* Call a function while guarding against errors that happens within it.
*
* @param {?String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} a First argument
* @param {*} b Second argument
*/
function invokeGuardedCallback(name, func, a, b) {
try {
return func(a, b);
} catch (x) {
if (caughtError === null) {
caughtError = x;
}
return undefined;
}
}
var ReactErrorUtils = {
invokeGuardedCallback: invokeGuardedCallback,
/**
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
* handler are sure to be rethrown by rethrowCaughtError.
*/
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
rethrowCaughtError: function () {
if (caughtError) {
var error = caughtError;
caughtError = null;
throw error;
}
}
};
if ("development" !== 'production') {
/**
* To help development we can get better devtools integration by simulating a
* real browser event.
*/
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
var fakeNode = document.createElement('react');
ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
var boundFunc = func.bind(null, a, b);
var evtType = 'react-' + name;
fakeNode.addEventListener(evtType, boundFunc, false);
var evt = document.createEvent('Event');
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
fakeNode.removeEventListener(evtType, boundFunc, false);
};
}
}
module.exports = ReactErrorUtils;
},{}],57:[function(_dereq_,module,exports){
/**
* 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 ReactEventEmitterMixin
*/
'use strict';
var EventPluginHub = _dereq_(16);
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue(false);
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native environment event.
*/
handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
},{"16":16}],58:[function(_dereq_,module,exports){
/**
* 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 ReactEventListener
* @typechecks static-only
*/
'use strict';
var EventListener = _dereq_(129);
var ExecutionEnvironment = _dereq_(130);
var PooledClass = _dereq_(24);
var ReactInstanceHandles = _dereq_(61);
var ReactMount = _dereq_(65);
var ReactUpdates = _dereq_(83);
var assign = _dereq_(23);
var getEventTarget = _dereq_(114);
var getUnboundedScrollPosition = _dereq_(141);
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
/**
* Finds the parent React component of `node`.
*
* @param {*} node
* @return {?DOMEventTarget} Parent container, or `null` if the specified node
* is not nested.
*/
function findParent(node) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
var nodeID = ReactMount.getID(node);
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
var container = ReactMount.findReactContainerForID(rootID);
var parent = ReactMount.getFirstReactDOM(container);
return parent;
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function () {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
function handleTopLevelImpl(bookKeeping) {
// TODO: Re-enable event.path handling
//
// if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) {
// // New browsers have a path attribute on native events
// handleTopLevelWithPath(bookKeeping);
// } else {
// // Legacy browsers don't have a path attribute on native events
// handleTopLevelWithoutPath(bookKeeping);
// }
void handleTopLevelWithPath; // temporarily unused
handleTopLevelWithoutPath(bookKeeping);
}
// Legacy browsers don't have a path attribute on native events
function handleTopLevelWithoutPath(bookKeeping) {
var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window;
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = topLevelTarget;
while (ancestor) {
bookKeeping.ancestors.push(ancestor);
ancestor = findParent(ancestor);
}
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
topLevelTarget = bookKeeping.ancestors[i];
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
// New browsers have a path attribute on native events
function handleTopLevelWithPath(bookKeeping) {
var path = bookKeeping.nativeEvent.path;
var currentNativeTarget = path[0];
var eventsFired = 0;
for (var i = 0; i < path.length; i++) {
var currentPathElement = path[i];
if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) {
currentNativeTarget = path[i + 1];
}
// TODO: slow
var reactParent = ReactMount.getFirstReactDOM(currentPathElement);
if (reactParent === currentPathElement) {
var currentPathElementID = ReactMount.getID(currentPathElement);
var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID);
bookKeeping.ancestors.push(currentPathElement);
var topLevelTargetID = ReactMount.getID(currentPathElement) || '';
eventsFired++;
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget);
// Jump to the root of this React render tree
while (currentPathElementID !== newRootID) {
i++;
currentPathElement = path[i];
currentPathElementID = ReactMount.getID(currentPathElement);
}
}
}
if (eventsFired === 0) {
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function (handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function (enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function () {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
monitorScrollValue: function (refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function (topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
},{"114":114,"129":129,"130":130,"141":141,"23":23,"24":24,"61":61,"65":65,"83":83}],59:[function(_dereq_,module,exports){
/**
* 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 ReactInjection
*/
'use strict';
var DOMProperty = _dereq_(10);
var EventPluginHub = _dereq_(16);
var ReactComponentEnvironment = _dereq_(32);
var ReactClass = _dereq_(29);
var ReactEmptyComponent = _dereq_(54);
var ReactBrowserEventEmitter = _dereq_(26);
var ReactNativeComponent = _dereq_(68);
var ReactPerf = _dereq_(71);
var ReactRootIndex = _dereq_(78);
var ReactUpdates = _dereq_(83);
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"10":10,"16":16,"26":26,"29":29,"32":32,"54":54,"68":68,"71":71,"78":78,"83":83}],60:[function(_dereq_,module,exports){
/**
* 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 ReactInputSelection
*/
'use strict';
var ReactDOMSelection = _dereq_(44);
var containsNode = _dereq_(133);
var focusNode = _dereq_(138);
var getActiveElement = _dereq_(139);
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function (elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true');
},
getSelectionInformation: function () {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function (priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function (input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || { start: 0, end: 0 };
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function (input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (typeof end === 'undefined') {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
},{"133":133,"138":138,"139":139,"44":44}],61:[function(_dereq_,module,exports){
/**
* 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 ReactInstanceHandles
* @typechecks static-only
*/
'use strict';
var ReactRootIndex = _dereq_(78);
var invariant = _dereq_(144);
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 10000;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR;
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length);
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
!(isValidID(ancestorID) && isValidID(destinationID)) ? "development" !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined;
!isAncestorIDOf(ancestorID, destinationID) ? "development" !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined;
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
var i;
for (i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @private
*/
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
!isValidID(longestCommonID) ? "development" !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined;
return longestCommonID;
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them. If the
* callback returns `false`, traversal is stopped.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {*} arg Argument to invoke the callback with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
!(start !== stop) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined;
var traverseUp = isAncestorIDOf(stop, start);
!(traverseUp || isAncestorIDOf(start, stop)) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined;
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start;; /* until break */id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
!(depth++ < MAX_TREE_DEPTH) ? "development" !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined;
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
/**
* Constructs a React root ID
* @return {string} A React root ID.
*/
createReactRootID: function () {
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function (rootID, name) {
return rootID + name;
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {?string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function (id) {
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
var index = id.indexOf(SEPARATOR, 1);
return index > -1 ? id.substr(0, index) : id;
}
return null;
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) {
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function (targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Same as `traverseTwoPhase` but skips the `targetID`.
*/
traverseTwoPhaseSkipTarget: function (targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, true);
traverseParentPath(targetID, '', cb, arg, true, true);
}
},
/**
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
* example, passing `.0.$row-0.1` would result in `cb` getting called
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseAncestors: function (targetID, cb, arg) {
traverseParentPath('', targetID, cb, arg, true, false);
},
getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
},{"144":144,"78":78}],62:[function(_dereq_,module,exports){
/**
* 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 ReactInstanceMap
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function (key) {
key._reactInternalInstance = undefined;
},
get: function (key) {
return key._reactInternalInstance;
},
has: function (key) {
return key._reactInternalInstance !== undefined;
},
set: function (key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
},{}],63:[function(_dereq_,module,exports){
/**
* 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 ReactIsomorphic
*/
'use strict';
var ReactChildren = _dereq_(28);
var ReactComponent = _dereq_(30);
var ReactClass = _dereq_(29);
var ReactDOMFactories = _dereq_(38);
var ReactElement = _dereq_(52);
var ReactElementValidator = _dereq_(53);
var ReactPropTypes = _dereq_(74);
var ReactVersion = _dereq_(84);
var assign = _dereq_(23);
var onlyChild = _dereq_(121);
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if ("development" !== 'production') {
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactComponent,
createElement: createElement,
cloneElement: cloneElement,
isValidElement: ReactElement.isValidElement,
// Classic
PropTypes: ReactPropTypes,
createClass: ReactClass.createClass,
createFactory: createFactory,
createMixin: function (mixin) {
// Currently a noop. Will be used to validate and trace mixins.
return mixin;
},
// This looks DOM specific but these are actually isomorphic helpers
// since they are just generating DOM strings.
DOM: ReactDOMFactories,
version: ReactVersion,
// Hook for JSX spread, don't use this for anything else.
__spread: assign
};
module.exports = React;
},{"121":121,"23":23,"28":28,"29":29,"30":30,"38":38,"52":52,"53":53,"74":74,"84":84}],64:[function(_dereq_,module,exports){
/**
* 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 ReactMarkupChecksum
*/
'use strict';
var adler32 = _dereq_(103);
var TAG_END = /\/?>/;
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function (markup) {
var checksum = adler32(markup);
// Add checksum (handle both parent tags and self-closing tags)
return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function (markup, element) {
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
},{"103":103}],65:[function(_dereq_,module,exports){
/**
* 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 ReactMount
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactBrowserEventEmitter = _dereq_(26);
var ReactCurrentOwner = _dereq_(34);
var ReactDOMFeatureFlags = _dereq_(39);
var ReactElement = _dereq_(52);
var ReactEmptyComponentRegistry = _dereq_(55);
var ReactInstanceHandles = _dereq_(61);
var ReactInstanceMap = _dereq_(62);
var ReactMarkupChecksum = _dereq_(64);
var ReactPerf = _dereq_(71);
var ReactReconciler = _dereq_(76);
var ReactUpdateQueue = _dereq_(82);
var ReactUpdates = _dereq_(83);
var assign = _dereq_(23);
var emptyObject = _dereq_(137);
var containsNode = _dereq_(133);
var instantiateReactComponent = _dereq_(118);
var invariant = _dereq_(144);
var setInnerHTML = _dereq_(124);
var shouldUpdateReactComponent = _dereq_(126);
var validateDOMNesting = _dereq_(128);
var warning = _dereq_(155);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2);
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if ("development" !== 'production') {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
// Used to store breadth-first search state in findComponentRoot.
var findComponentRootReusableArray = [];
/**
* Finds the index of the first character
* that's not common between the two given strings.
*
* @return {number} the index of the character where the strings diverge
*/
function firstDifferenceIndex(string1, string2) {
var minLen = Math.min(string1.length, string2.length);
for (var i = 0; i < minLen; i++) {
if (string1.charAt(i) !== string2.charAt(i)) {
return i;
}
}
return string1.length === string2.length ? -1 : minLen;
}
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
/**
* @param {DOMElement} container DOM element that may contain a React component.
* @return {?string} A "reactRoot" ID, if a React component is rendered.
*/
function getReactRootID(container) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
/**
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
* element can return its control whose name or ID equals ATTR_NAME. All
* DOM nodes support `getAttributeNode` but this can also get called on
* other objects so just return '' if we're given something other than a
* DOM node (such as window).
*
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
* @return {string} ID of the supplied `domNode`.
*/
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
!!isValid(cached, id) ? "development" !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined;
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Sets the React-specific ID of the given node.
*
* @param {DOMElement} node The DOM node whose ID will be set.
* @param {string} id The value of the ID attribute.
*/
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
/**
* Finds the node with the supplied React-generated DOM ID.
*
* @param {string} id A React-generated DOM ID.
* @return {DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* Finds the node with the supplied public React instance.
*
* @param {*} instance A public React instance.
* @return {?DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNodeFromInstance(instance) {
var id = ReactInstanceMap.get(instance)._rootNodeID;
if (ReactEmptyComponentRegistry.isNullComponentID(id)) {
return null;
}
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* A node is "valid" if it is contained by a currently mounted container.
*
* This means that the node does not have to be contained by a document in
* order to be considered valid.
*
* @param {?DOMElement} node The candidate DOM node.
* @param {string} id The expected ID of the node.
* @return {boolean} Whether the node is contained by a mounted container.
*/
function isValid(node, id) {
if (node) {
!(internalGetID(node) === id) ? "development" !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined;
var container = ReactMount.findReactContainerForID(id);
if (container && containsNode(container, node)) {
return true;
}
}
return false;
}
/**
* Causes the cache to forget about one React-specific ID.
*
* @param {string} id The ID to forget.
*/
function purgeID(id) {
delete nodeCache[id];
}
var deepestNodeSoFar = null;
function findDeepestCachedAncestorImpl(ancestorID) {
var ancestor = nodeCache[ancestorID];
if (ancestor && isValid(ancestor, ancestorID)) {
deepestNodeSoFar = ancestor;
} else {
// This node isn't populated in the cache, so presumably none of its
// descendants are. Break out of the loop.
return false;
}
}
/**
* Return the deepest cached node whose ID is a prefix of `targetID`.
*/
function findDeepestCachedAncestor(targetID) {
deepestNodeSoFar = null;
ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl);
var foundNode = deepestNodeSoFar;
deepestNodeSoFar = null;
return foundNode;
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) {
if (ReactDOMFeatureFlags.useCreateElement) {
context = assign({}, context);
if (container.nodeType === DOC_NODE_TYPE) {
context[ownerDocumentContextKey] = container;
} else {
context[ownerDocumentContextKey] = container.ownerDocument;
}
}
if ("development" !== 'production') {
if (context === emptyObject) {
context = {};
}
var tag = container.nodeName.toLowerCase();
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null);
}
var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context);
componentInstance._renderedComponent._topLevelWrapper = componentInstance;
ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* forceHTML */shouldReuseMarkup);
transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
function unmountComponentFromNode(instance, container) {
ReactReconciler.unmountComponent(instance);
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
}
/**
* True if the supplied DOM node has a direct React-rendered child that is
* not a React root element. Useful for warning in `render`,
* `unmountComponentAtNode`, etc.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM element contains a direct child that was
* rendered by React but is not a root element.
* @internal
*/
function hasNonRootReactChild(node) {
var reactRootID = getReactRootID(node);
return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false;
}
/**
* Returns the first (deepest) ancestor of a node which is rendered by this copy
* of React.
*/
function findFirstReactDOMImpl(node) {
// This node might be from another React instance, so we make sure not to
// examine the node cache here
for (; node && node.parentNode !== node; node = node.parentNode) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
continue;
}
var nodeID = internalGetID(node);
if (!nodeID) {
continue;
}
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
// If containersByReactRootID contains the container we find by crawling up
// the tree, we know that this instance of React rendered the node.
// nb. isValid's strategy (with containsNode) does not work because render
// trees may be nested and we don't want a false positive in that case.
var current = node;
var lastID;
do {
lastID = internalGetID(current);
current = current.parentNode;
if (current == null) {
// The passed-in node has been detached from the container it was
// originally rendered into.
return null;
}
} while (lastID !== reactRootID);
if (current === containersByReactRootID[reactRootID]) {
return node;
}
}
return null;
}
/**
* Temporary (?) hack so that we can store all top-level pending updates on
* composites instead of having to worry about different types of components
* here.
*/
var TopLevelWrapper = function () {};
TopLevelWrapper.prototype.isReactComponent = {};
if ("development" !== 'production') {
TopLevelWrapper.displayName = 'TopLevelWrapper';
}
TopLevelWrapper.prototype.render = function () {
// this.props is actually a ReactElement
return this.props;
};
/**
* Mounting is the process of initializing a React component by creating its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.render(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
TopLevelWrapper: TopLevelWrapper,
/** Exposed for debugging purposes **/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function (container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactElement} nextElement component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function (prevComponent, nextElement, container, callback) {
ReactMount.scrollMonitor(container, function () {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
if ("development" !== 'production') {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container);
}
return prevComponent;
},
/**
* Register a component into the instance map and starts scroll value
* monitoring
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @return {string} reactRoot ID prefix
*/
_registerComponent: function (nextComponent, container) {
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactElement} nextElement element to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
"development" !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
var componentInstance = instantiateReactComponent(nextElement, null);
var reactRootID = ReactMount._registerComponent(componentInstance, container);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context);
if ("development" !== 'production') {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container);
}
return componentInstance;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} parentComponent The conceptual parent of this render tree.
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!(parentComponent != null && parentComponent._reactInternalInstance != null) ? "development" !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined;
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
},
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!ReactElement.isValidElement(nextElement) ? "development" !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined;
"development" !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined;
var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement);
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement;
var prevElement = prevWrappedElement.props;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
var publicInst = prevComponent._renderedComponent.getPublicInstance();
var updatedCallback = callback && function () {
callback.call(publicInst);
};
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback);
return publicInst;
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
var containerHasNonRootReactChild = hasNonRootReactChild(container);
if ("development" !== 'production') {
"development" !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined;
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
var rootElementSibling = reactRootElement;
while (rootElementSibling) {
if (internalGetID(rootElementSibling)) {
"development" !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined;
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
render: function (nextElement, container, callback) {
return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reactRoot" ID that will be assigned to the element
* rendered within.
*
* @param {DOMElement} container DOM element to register as a container.
* @return {string} The "reactRoot" ID of elements rendered within.
*/
registerContainer: function (container) {
var reactRootID = getReactRootID(container);
if (reactRootID) {
// If one exists, make sure it is a valid "reactRoot" ID.
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
}
if (!reactRootID) {
// No valid "reactRoot" ID found, create one.
reactRootID = ReactInstanceHandles.createReactRootID();
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function (container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
"development" !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined;
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
// Check if the node being unmounted was rendered by React, but isn't a
// root node.
var containerHasNonRootReactChild = hasNonRootReactChild(container);
// Check if the container itself is a React root node.
var containerID = internalGetID(container);
var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID);
if ("development" !== 'production') {
"development" !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined;
}
return false;
}
ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if ("development" !== 'production') {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* Finds the container DOM element that contains React component to which the
* supplied DOM `id` belongs.
*
* @param {string} id The ID of an element rendered by a React component.
* @return {?DOMElement} DOM element that contains the `id`.
*/
findReactContainerForID: function (id) {
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
var container = containersByReactRootID[reactRootID];
if ("development" !== 'production') {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
"development" !== 'production' ? warning(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined;
var containerChild = container.firstChild;
if (containerChild && reactRootID === internalGetID(containerChild)) {
// If the container has a new child with the same ID as the old
// root element, then rootElementsByReactRootID[reactRootID] is
// just stale and needs to be updated. The case that deserves a
// warning is when the container is empty.
rootElementsByReactRootID[reactRootID] = containerChild;
} else {
"development" !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined;
}
}
}
return container;
},
/**
* Finds an element rendered by React with the supplied ID.
*
* @param {string} id ID of a DOM node in the React component.
* @return {DOMElement} Root DOM node of the React component.
*/
findReactNodeByID: function (id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactMount.findComponentRoot(reactRoot, id);
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component rendered by this copy of React.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function (node) {
return findFirstReactDOMImpl(node);
},
/**
* Finds a node with the supplied `targetID` inside of the supplied
* `ancestorNode`. Exploits the ID naming scheme to perform the search
* quickly.
*
* @param {DOMEventTarget} ancestorNode Search from this root.
* @pararm {string} targetID ID of the DOM representation of the component.
* @return {DOMEventTarget} DOM node with the supplied `targetID`.
* @internal
*/
findComponentRoot: function (ancestorNode, targetID) {
var firstChildren = findComponentRootReusableArray;
var childIndex = 0;
var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
if ("development" !== 'production') {
// This will throw on the next line; give an early warning
"development" !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined;
}
firstChildren[0] = deepestAncestor.firstChild;
firstChildren.length = 1;
while (childIndex < firstChildren.length) {
var child = firstChildren[childIndex++];
var targetChild;
while (child) {
var childID = ReactMount.getID(child);
if (childID) {
// Even if we find the node we're looking for, we finish looping
// through its siblings to ensure they're cached so that we don't have
// to revisit this node again. Otherwise, we make n^2 calls to getID
// when visiting the many children of a single node in order.
if (targetID === childID) {
targetChild = child;
} else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
// If we find a child whose ID is an ancestor of the given ID,
// then we can be sure that we only want to search the subtree
// rooted at this child, so we can throw out the rest of the
// search state.
firstChildren.length = childIndex = 0;
firstChildren.push(child.firstChild);
}
} else {
// If this child had no ID, then there's a chance that it was
// injected automatically by the browser, as when a `<table>`
// element sprouts an extra `<tbody>` child as a side effect of
// `.innerHTML` parsing. Optimistically continue down this
// branch, but not before examining the other siblings.
firstChildren.push(child.firstChild);
}
child = child.nextSibling;
}
if (targetChild) {
// Emptying firstChildren/findComponentRootReusableArray is
// not necessary for correctness, but it helps the GC reclaim
// any nodes that were left at the end of the search.
firstChildren.length = 0;
return targetChild;
}
}
firstChildren.length = 0;
!false ? "development" !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined;
},
_mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) {
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined;
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
return;
} else {
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
var normalizedMarkup = markup;
if ("development" !== 'production') {
// because rootMarkup is retrieved from the DOM, various normalizations
// will have occurred which will not be present in `markup`. Here,
// insert markup into a <div> or <iframe> depending on the container
// type to perform the same normalizations before comparing.
var normalizer;
if (container.nodeType === ELEMENT_NODE_TYPE) {
normalizer = document.createElement('div');
normalizer.innerHTML = markup;
normalizedMarkup = normalizer.innerHTML;
} else {
normalizer = document.createElement('iframe');
document.body.appendChild(normalizer);
normalizer.contentDocument.write(markup);
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
document.body.removeChild(normalizer);
}
}
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
!(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined;
}
}
}
!(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
if (transaction.useCreateElement) {
while (container.lastChild) {
container.removeChild(container.lastChild);
}
container.appendChild(markup);
} else {
setInnerHTML(container, markup);
}
},
ownerDocumentContextKey: ownerDocumentContextKey,
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
getNodeFromInstance: getNodeFromInstance,
isValid: isValid,
purgeID: purgeID
};
ReactPerf.measureMethods(ReactMount, 'ReactMount', {
_renderNewRootComponent: '_renderNewRootComponent',
_mountImageIntoNode: '_mountImageIntoNode'
});
module.exports = ReactMount;
},{"10":10,"118":118,"124":124,"126":126,"128":128,"133":133,"137":137,"144":144,"155":155,"23":23,"26":26,"34":34,"39":39,"52":52,"55":55,"61":61,"62":62,"64":64,"71":71,"76":76,"82":82,"83":83}],66:[function(_dereq_,module,exports){
/**
* 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 ReactMultiChild
* @typechecks static-only
*/
'use strict';
var ReactComponentEnvironment = _dereq_(32);
var ReactMultiChildUpdateTypes = _dereq_(67);
var ReactCurrentOwner = _dereq_(34);
var ReactReconciler = _dereq_(76);
var ReactChildReconciler = _dereq_(27);
var flattenChildren = _dereq_(109);
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueInsertMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
content: null,
fromIndex: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the markup of a node.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @private
*/
function enqueueSetMarkup(parentID, markup) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.SET_MARKUP,
markupIndex: null,
content: markup,
fromIndex: null,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
content: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
_reconcilerInstantiateChildren: function (nestedChildren, transaction, context) {
if ("development" !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
} finally {
ReactCurrentOwner.current = null;
}
}
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) {
var nextChildren;
if ("development" !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements);
} finally {
ReactCurrentOwner.current = null;
}
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
}
}
nextChildren = flattenChildren(nextNestedChildrenElements);
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
},
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function (nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
child._mountIndex = index++;
mountImages.push(mountImage);
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function (nextContent) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
// TODO: The setTextContent operation should be enough
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChild(prevChildren[name]);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function (nextMarkup) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
this.setMarkup(nextMarkup);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function (nextNestedChildrenElements, transaction, context) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildrenElements, transaction, context);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren;
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context);
this._renderedChildren = nextChildren;
if (!nextChildren && !prevChildren) {
return;
}
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChild(prevChild);
}
// The child must be instantiated before it's mounted.
this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
this._unmountChild(prevChildren[name]);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function () {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function (child, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function (child, mountImage) {
enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function (child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function (textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* Sets this markup string.
*
* @param {string} markup Markup to set.
* @protected
*/
setMarkup: function (markup) {
enqueueSetMarkup(this._rootNodeID, markup);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildByNameAtIndex: function (child, name, index, transaction, context) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
child._mountIndex = index;
this.createChild(child, mountImage);
},
/**
* Unmounts a rendered child.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @private
*/
_unmountChild: function (child) {
this.removeChild(child);
child._mountIndex = null;
}
}
};
module.exports = ReactMultiChild;
},{"109":109,"27":27,"32":32,"34":34,"67":67,"76":76}],67:[function(_dereq_,module,exports){
/**
* 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 ReactMultiChildUpdateTypes
*/
'use strict';
var keyMirror = _dereq_(147);
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
SET_MARKUP: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
},{"147":147}],68:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeComponent
*/
'use strict';
var assign = _dereq_(23);
var invariant = _dereq_(144);
var autoGenerateWrapperClass = null;
var genericComponentClass = null;
// This registry keeps track of wrapper classes around native tags.
var tagToComponentClass = {};
var textComponentClass = null;
var ReactNativeComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function (componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function (componentClass) {
textComponentClass = componentClass;
},
// This accepts a keyed object with classes as values. Each key represents a
// tag. That particular tag will use this class instead of the generic one.
injectComponentClasses: function (componentClasses) {
assign(tagToComponentClass, componentClasses);
}
};
/**
* Get a composite component wrapper class for a specific tag.
*
* @param {ReactElement} element The tag for which to get the class.
* @return {function} The React class constructor function.
*/
function getComponentClassForElement(element) {
if (typeof element.type === 'function') {
return element.type;
}
var tag = element.type;
var componentClass = tagToComponentClass[tag];
if (componentClass == null) {
tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
}
return componentClass;
}
/**
* Get a native internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
!genericComponentClass ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined;
return new genericComponentClass(element.type, element.props);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactNativeComponent = {
getComponentClassForElement: getComponentClassForElement,
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactNativeComponentInjection
};
module.exports = ReactNativeComponent;
},{"144":144,"23":23}],69:[function(_dereq_,module,exports){
/**
* Copyright 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 ReactNoopUpdateQueue
*/
'use strict';
var warning = _dereq_(155);
function warnTDZ(publicInstance, callerName) {
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
warnTDZ(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
warnTDZ(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
warnTDZ(publicInstance, 'setState');
},
/**
* Sets a subset of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialProps Subset of the next props.
* @internal
*/
enqueueSetProps: function (publicInstance, partialProps) {
warnTDZ(publicInstance, 'setProps');
},
/**
* Replaces all of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} props New props.
* @internal
*/
enqueueReplaceProps: function (publicInstance, props) {
warnTDZ(publicInstance, 'replaceProps');
}
};
module.exports = ReactNoopUpdateQueue;
},{"155":155}],70:[function(_dereq_,module,exports){
/**
* 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 ReactOwner
*/
'use strict';
var invariant = _dereq_(144);
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function (object) {
return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
},{"144":144}],71:[function(_dereq_,module,exports){
/**
* 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 ReactPerf
* @typechecks static-only
*/
'use strict';
/**
* ReactPerf is a general AOP system designed to measure performance. This
* module only has the hooks: see ReactDefaultPerf for the analysis tool.
*/
var ReactPerf = {
/**
* Boolean to enable/disable measurement. Set to false by default to prevent
* accidental logging and perf loss.
*/
enableMeasure: false,
/**
* Holds onto the measure function in use. By default, don't measure
* anything, but we'll override this if we inject a measure function.
*/
storedMeasure: _noMeasure,
/**
* @param {object} object
* @param {string} objectName
* @param {object<string>} methodNames
*/
measureMethods: function (object, objectName, methodNames) {
if ("development" !== 'production') {
for (var key in methodNames) {
if (!methodNames.hasOwnProperty(key)) {
continue;
}
object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]);
}
}
},
/**
* Use this to wrap methods you want to measure. Zero overhead in production.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function (objName, fnName, func) {
if ("development" !== 'production') {
var measuredFunc = null;
var wrapper = function () {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
wrapper.displayName = objName + '_' + fnName;
return wrapper;
}
return func;
},
injection: {
/**
* @param {function} measure
*/
injectMeasure: function (measure) {
ReactPerf.storedMeasure = measure;
}
}
};
/**
* Simply passes through the measured function, without measuring it.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
function _noMeasure(objName, fnName, func) {
return func;
}
module.exports = ReactPerf;
},{}],72:[function(_dereq_,module,exports){
/**
* 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 ReactPropTypeLocationNames
*/
'use strict';
var ReactPropTypeLocationNames = {};
if ("development" !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],73:[function(_dereq_,module,exports){
/**
* 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 ReactPropTypeLocations
*/
'use strict';
var keyMirror = _dereq_(147);
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
},{"147":147}],74:[function(_dereq_,module,exports){
/**
* 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 ReactPropTypes
*/
'use strict';
var ReactElement = _dereq_(52);
var ReactPropTypeLocationNames = _dereq_(72);
var emptyFunction = _dereq_(136);
var getIteratorFn = _dereq_(115);
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']');
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOf, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOfType, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return '<<anonymous>>';
}
return propValue.constructor.name;
}
module.exports = ReactPropTypes;
},{"115":115,"136":136,"52":52,"72":72}],75:[function(_dereq_,module,exports){
/**
* 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 ReactReconcileTransaction
* @typechecks static-only
*/
'use strict';
var CallbackQueue = _dereq_(6);
var PooledClass = _dereq_(24);
var ReactBrowserEventEmitter = _dereq_(26);
var ReactDOMFeatureFlags = _dereq_(39);
var ReactInputSelection = _dereq_(60);
var Transaction = _dereq_(100);
var assign = _dereq_(23);
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function () {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
* restores the previous value.
*/
close: function (previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function () {
this.reactMountReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction(forceHTML) {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"100":100,"23":23,"24":24,"26":26,"39":39,"6":6,"60":60}],76:[function(_dereq_,module,exports){
/**
* 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 ReactReconciler
*/
'use strict';
var ReactRef = _dereq_(77);
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (internalInstance, rootID, transaction, context) {
var markup = internalInstance.mountComponent(rootID, transaction, context);
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (internalInstance) {
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent();
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function (internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement === prevElement && context === internalInstance._context) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for an element created outside a composite to be
// deeply mutated and reused.
// TODO: Bailing out early is just a perf optimization right?
// TODO: Removing the return statement should affect correctness?
return;
}
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
if (refsChanged) {
ReactRef.detachRefs(internalInstance, prevElement);
}
internalInstance.receiveComponent(nextElement, transaction, context);
if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (internalInstance, transaction) {
internalInstance.performUpdateIfNecessary(transaction);
}
};
module.exports = ReactReconciler;
},{"77":77}],77:[function(_dereq_,module,exports){
/**
* 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 ReactRef
*/
'use strict';
var ReactOwner = _dereq_(70);
var ReactRef = {};
function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
}
function detachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(null);
} else {
// Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
}
ReactRef.attachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
attachRef(ref, instance, element._owner);
}
};
ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
return(
// This has a few false positives w/r/t empty components.
prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref
);
};
ReactRef.detachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
detachRef(ref, instance, element._owner);
}
};
module.exports = ReactRef;
},{"70":70}],78:[function(_dereq_,module,exports){
/**
* 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 ReactRootIndex
* @typechecks
*/
'use strict';
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function (_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
},{}],79:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerBatchingStrategy
* @typechecks
*/
'use strict';
var ReactServerBatchingStrategy = {
isBatchingUpdates: false,
batchedUpdates: function (callback) {
// Don't do anything here. During the server rendering we don't want to
// schedule any updates. We will simply ignore them.
}
};
module.exports = ReactServerBatchingStrategy;
},{}],80:[function(_dereq_,module,exports){
/**
* 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.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
'use strict';
var ReactDefaultBatchingStrategy = _dereq_(48);
var ReactElement = _dereq_(52);
var ReactInstanceHandles = _dereq_(61);
var ReactMarkupChecksum = _dereq_(64);
var ReactServerBatchingStrategy = _dereq_(79);
var ReactServerRenderingTransaction = _dereq_(81);
var ReactUpdates = _dereq_(83);
var emptyObject = _dereq_(137);
var instantiateReactComponent = _dereq_(118);
var invariant = _dereq_(144);
/**
* @param {ReactElement} element
* @return {string} the HTML markup
*/
function renderToString(element) {
!ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
var markup = componentInstance.mountComponent(id, transaction, emptyObject);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
/**
* @param {ReactElement} element
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderToStaticMarkup(element) {
!ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
return componentInstance.mountComponent(id, transaction, emptyObject);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
module.exports = {
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup
};
},{"118":118,"137":137,"144":144,"48":48,"52":52,"61":61,"64":64,"79":79,"81":81,"83":83}],81:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerRenderingTransaction
* @typechecks
*/
'use strict';
var PooledClass = _dereq_(24);
var CallbackQueue = _dereq_(6);
var Transaction = _dereq_(100);
var assign = _dereq_(23);
var emptyFunction = _dereq_(136);
/**
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks
* during the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
close: emptyFunction
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING];
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = false;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap procedures.
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
},{"100":100,"136":136,"23":23,"24":24,"6":6}],82:[function(_dereq_,module,exports){
/**
* Copyright 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 ReactUpdateQueue
*/
'use strict';
var ReactCurrentOwner = _dereq_(34);
var ReactElement = _dereq_(52);
var ReactInstanceMap = _dereq_(62);
var ReactUpdates = _dereq_(83);
var assign = _dereq_(23);
var invariant = _dereq_(144);
var warning = _dereq_(155);
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if ("development" !== 'production') {
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
"development" !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined;
}
return null;
}
if ("development" !== 'production') {
"development" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined;
}
return internalInstance;
}
/**
* ReactUpdateQueue allows for state updates to be scheduled into a later
* reconciliation step.
*/
var ReactUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
if ("development" !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
"development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(publicInstance);
if (internalInstance) {
// During componentWillMount and render this will still be null but after
// that will always render to something. At least for now. So we can use
// this hack.
return !!internalInstance._renderedComponent;
} else {
return false;
}
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {
!(typeof callback === 'function') ? "development" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function (internalInstance, callback) {
!(typeof callback === 'function') ? "development" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
if (!internalInstance) {
return;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
if (!internalInstance) {
return;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialProps Subset of the next props.
* @internal
*/
enqueueSetProps: function (publicInstance, partialProps) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps');
if (!internalInstance) {
return;
}
ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps);
},
enqueueSetPropsInternal: function (internalInstance, partialProps) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? "development" !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
// Merge with the pending element if it exists, otherwise with existing
// element props.
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
var props = assign({}, element.props, partialProps);
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
/**
* Replaces all of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} props New props.
* @internal
*/
enqueueReplaceProps: function (publicInstance, props) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps');
if (!internalInstance) {
return;
}
ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props);
},
enqueueReplacePropsInternal: function (internalInstance, props) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? "development" !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
// Merge with the pending element if it exists, otherwise with existing
// element props.
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
enqueueElementInternal: function (internalInstance, newElement) {
internalInstance._pendingElement = newElement;
enqueueUpdate(internalInstance);
}
};
module.exports = ReactUpdateQueue;
},{"144":144,"155":155,"23":23,"34":34,"52":52,"62":62,"83":83}],83:[function(_dereq_,module,exports){
/**
* 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 ReactUpdates
*/
'use strict';
var CallbackQueue = _dereq_(6);
var PooledClass = _dereq_(24);
var ReactPerf = _dereq_(71);
var ReactReconciler = _dereq_(76);
var Transaction = _dereq_(100);
var assign = _dereq_(23);
var invariant = _dereq_(144);
var dirtyComponents = [];
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
!(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined;
}
var NESTED_UPDATES = {
initialize: function () {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function () {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function () {
this.callbackQueue.reset();
},
close: function () {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled();
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false);
}
assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
destructor: function () {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function (method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
!(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined;
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i];
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction);
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
}
}
}
}
var flushBatchedUpdates = function () {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = false;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled();
queue.notifyAll();
CallbackQueue.release(queue);
}
}
};
flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates);
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
!batchingStrategy.isBatchingUpdates ? "development" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined;
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function (ReconcileTransaction) {
!ReconcileTransaction ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined;
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function (_batchingStrategy) {
!_batchingStrategy ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined;
!(typeof _batchingStrategy.batchedUpdates === 'function') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined;
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined;
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
},{"100":100,"144":144,"23":23,"24":24,"6":6,"71":71,"76":76}],84:[function(_dereq_,module,exports){
/**
* 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 ReactVersion
*/
'use strict';
module.exports = '0.14.7';
},{}],85:[function(_dereq_,module,exports){
/**
* 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 SVGDOMPropertyConfig
*/
'use strict';
var DOMProperty = _dereq_(10);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var NS = {
xlink: 'http://www.w3.org/1999/xlink',
xml: 'http://www.w3.org/XML/1998/namespace'
};
var SVGDOMPropertyConfig = {
Properties: {
clipPath: MUST_USE_ATTRIBUTE,
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
dx: MUST_USE_ATTRIBUTE,
dy: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fillOpacity: MUST_USE_ATTRIBUTE,
fontFamily: MUST_USE_ATTRIBUTE,
fontSize: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
markerEnd: MUST_USE_ATTRIBUTE,
markerMid: MUST_USE_ATTRIBUTE,
markerStart: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
opacity: MUST_USE_ATTRIBUTE,
patternContentUnits: MUST_USE_ATTRIBUTE,
patternUnits: MUST_USE_ATTRIBUTE,
points: MUST_USE_ATTRIBUTE,
preserveAspectRatio: MUST_USE_ATTRIBUTE,
r: MUST_USE_ATTRIBUTE,
rx: MUST_USE_ATTRIBUTE,
ry: MUST_USE_ATTRIBUTE,
spreadMethod: MUST_USE_ATTRIBUTE,
stopColor: MUST_USE_ATTRIBUTE,
stopOpacity: MUST_USE_ATTRIBUTE,
stroke: MUST_USE_ATTRIBUTE,
strokeDasharray: MUST_USE_ATTRIBUTE,
strokeLinecap: MUST_USE_ATTRIBUTE,
strokeOpacity: MUST_USE_ATTRIBUTE,
strokeWidth: MUST_USE_ATTRIBUTE,
textAnchor: MUST_USE_ATTRIBUTE,
transform: MUST_USE_ATTRIBUTE,
version: MUST_USE_ATTRIBUTE,
viewBox: MUST_USE_ATTRIBUTE,
x1: MUST_USE_ATTRIBUTE,
x2: MUST_USE_ATTRIBUTE,
x: MUST_USE_ATTRIBUTE,
xlinkActuate: MUST_USE_ATTRIBUTE,
xlinkArcrole: MUST_USE_ATTRIBUTE,
xlinkHref: MUST_USE_ATTRIBUTE,
xlinkRole: MUST_USE_ATTRIBUTE,
xlinkShow: MUST_USE_ATTRIBUTE,
xlinkTitle: MUST_USE_ATTRIBUTE,
xlinkType: MUST_USE_ATTRIBUTE,
xmlBase: MUST_USE_ATTRIBUTE,
xmlLang: MUST_USE_ATTRIBUTE,
xmlSpace: MUST_USE_ATTRIBUTE,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNamespaces: {
xlinkActuate: NS.xlink,
xlinkArcrole: NS.xlink,
xlinkHref: NS.xlink,
xlinkRole: NS.xlink,
xlinkShow: NS.xlink,
xlinkTitle: NS.xlink,
xlinkType: NS.xlink,
xmlBase: NS.xml,
xmlLang: NS.xml,
xmlSpace: NS.xml
},
DOMAttributeNames: {
clipPath: 'clip-path',
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
patternContentUnits: 'patternContentUnits',
patternUnits: 'patternUnits',
preserveAspectRatio: 'preserveAspectRatio',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox',
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space'
}
};
module.exports = SVGDOMPropertyConfig;
},{"10":10}],86:[function(_dereq_,module,exports){
/**
* 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 SelectEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(19);
var ExecutionEnvironment = _dereq_(130);
var ReactInputSelection = _dereq_(60);
var SyntheticEvent = _dereq_(92);
var getActiveElement = _dereq_(139);
var isTextInputElement = _dereq_(120);
var keyOf = _dereq_(148);
var shallowEqual = _dereq_(153);
var topLevelTypes = EventConstants.topLevelTypes;
var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({ onSelect: null }),
captured: keyOf({ onSelectCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange]
}
};
var activeElement = null;
var activeElementID = null;
var lastSelection = null;
var mouseDown = false;
// Track whether a listener exists for this plugin. If none exist, we do
// not extract events.
var hasListener = false;
var ON_SELECT_KEY = keyOf({ onSelect: null });
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @return {object}
*/
function getSelection(node) {
if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown || activeElement == null || activeElement !== getActiveElement()) {
return null;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
return null;
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
if (!hasListener) {
return null;
}
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') {
activeElement = topLevelTarget;
activeElementID = topLevelTargetID;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementID = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent, nativeEventTarget);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case topLevelTypes.topSelectionChange:
if (skipSelectionChangeEvent) {
break;
}
// falls through
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent, nativeEventTarget);
}
return null;
},
didPutListener: function (id, registrationName, listener) {
if (registrationName === ON_SELECT_KEY) {
hasListener = true;
}
}
};
module.exports = SelectEventPlugin;
},{"120":120,"130":130,"139":139,"148":148,"15":15,"153":153,"19":19,"60":60,"92":92}],87:[function(_dereq_,module,exports){
/**
* 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 ServerReactRootIndex
* @typechecks
*/
'use strict';
/**
* Size of the reactRoot ID space. We generate random numbers for React root
* IDs and if there's a collision the events and DOM update system will
* get confused. In the future we need a way to generate GUIDs but for
* now this will work on a smaller scale.
*/
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var ServerReactRootIndex = {
createReactRootIndex: function () {
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = ServerReactRootIndex;
},{}],88:[function(_dereq_,module,exports){
/**
* 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 SimpleEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventListener = _dereq_(129);
var EventPropagators = _dereq_(19);
var ReactMount = _dereq_(65);
var SyntheticClipboardEvent = _dereq_(89);
var SyntheticEvent = _dereq_(92);
var SyntheticFocusEvent = _dereq_(93);
var SyntheticKeyboardEvent = _dereq_(95);
var SyntheticMouseEvent = _dereq_(96);
var SyntheticDragEvent = _dereq_(91);
var SyntheticTouchEvent = _dereq_(97);
var SyntheticUIEvent = _dereq_(98);
var SyntheticWheelEvent = _dereq_(99);
var emptyFunction = _dereq_(136);
var getEventCharCode = _dereq_(111);
var invariant = _dereq_(144);
var keyOf = _dereq_(148);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
abort: {
phasedRegistrationNames: {
bubbled: keyOf({ onAbort: true }),
captured: keyOf({ onAbortCapture: true })
}
},
blur: {
phasedRegistrationNames: {
bubbled: keyOf({ onBlur: true }),
captured: keyOf({ onBlurCapture: true })
}
},
canPlay: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlay: true }),
captured: keyOf({ onCanPlayCapture: true })
}
},
canPlayThrough: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlayThrough: true }),
captured: keyOf({ onCanPlayThroughCapture: true })
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({ onClick: true }),
captured: keyOf({ onClickCapture: true })
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({ onContextMenu: true }),
captured: keyOf({ onContextMenuCapture: true })
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({ onCopy: true }),
captured: keyOf({ onCopyCapture: true })
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({ onCut: true }),
captured: keyOf({ onCutCapture: true })
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({ onDoubleClick: true }),
captured: keyOf({ onDoubleClickCapture: true })
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrag: true }),
captured: keyOf({ onDragCapture: true })
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnd: true }),
captured: keyOf({ onDragEndCapture: true })
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnter: true }),
captured: keyOf({ onDragEnterCapture: true })
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragExit: true }),
captured: keyOf({ onDragExitCapture: true })
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragLeave: true }),
captured: keyOf({ onDragLeaveCapture: true })
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragOver: true }),
captured: keyOf({ onDragOverCapture: true })
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragStart: true }),
captured: keyOf({ onDragStartCapture: true })
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrop: true }),
captured: keyOf({ onDropCapture: true })
}
},
durationChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onDurationChange: true }),
captured: keyOf({ onDurationChangeCapture: true })
}
},
emptied: {
phasedRegistrationNames: {
bubbled: keyOf({ onEmptied: true }),
captured: keyOf({ onEmptiedCapture: true })
}
},
encrypted: {
phasedRegistrationNames: {
bubbled: keyOf({ onEncrypted: true }),
captured: keyOf({ onEncryptedCapture: true })
}
},
ended: {
phasedRegistrationNames: {
bubbled: keyOf({ onEnded: true }),
captured: keyOf({ onEndedCapture: true })
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({ onError: true }),
captured: keyOf({ onErrorCapture: true })
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({ onFocus: true }),
captured: keyOf({ onFocusCapture: true })
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({ onInput: true }),
captured: keyOf({ onInputCapture: true })
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyDown: true }),
captured: keyOf({ onKeyDownCapture: true })
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyPress: true }),
captured: keyOf({ onKeyPressCapture: true })
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyUp: true }),
captured: keyOf({ onKeyUpCapture: true })
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoad: true }),
captured: keyOf({ onLoadCapture: true })
}
},
loadedData: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedData: true }),
captured: keyOf({ onLoadedDataCapture: true })
}
},
loadedMetadata: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedMetadata: true }),
captured: keyOf({ onLoadedMetadataCapture: true })
}
},
loadStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadStart: true }),
captured: keyOf({ onLoadStartCapture: true })
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseDown: true }),
captured: keyOf({ onMouseDownCapture: true })
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseMove: true }),
captured: keyOf({ onMouseMoveCapture: true })
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOut: true }),
captured: keyOf({ onMouseOutCapture: true })
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOver: true }),
captured: keyOf({ onMouseOverCapture: true })
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseUp: true }),
captured: keyOf({ onMouseUpCapture: true })
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({ onPaste: true }),
captured: keyOf({ onPasteCapture: true })
}
},
pause: {
phasedRegistrationNames: {
bubbled: keyOf({ onPause: true }),
captured: keyOf({ onPauseCapture: true })
}
},
play: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlay: true }),
captured: keyOf({ onPlayCapture: true })
}
},
playing: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlaying: true }),
captured: keyOf({ onPlayingCapture: true })
}
},
progress: {
phasedRegistrationNames: {
bubbled: keyOf({ onProgress: true }),
captured: keyOf({ onProgressCapture: true })
}
},
rateChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onRateChange: true }),
captured: keyOf({ onRateChangeCapture: true })
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({ onReset: true }),
captured: keyOf({ onResetCapture: true })
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({ onScroll: true }),
captured: keyOf({ onScrollCapture: true })
}
},
seeked: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeked: true }),
captured: keyOf({ onSeekedCapture: true })
}
},
seeking: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeking: true }),
captured: keyOf({ onSeekingCapture: true })
}
},
stalled: {
phasedRegistrationNames: {
bubbled: keyOf({ onStalled: true }),
captured: keyOf({ onStalledCapture: true })
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({ onSubmit: true }),
captured: keyOf({ onSubmitCapture: true })
}
},
suspend: {
phasedRegistrationNames: {
bubbled: keyOf({ onSuspend: true }),
captured: keyOf({ onSuspendCapture: true })
}
},
timeUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onTimeUpdate: true }),
captured: keyOf({ onTimeUpdateCapture: true })
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchCancel: true }),
captured: keyOf({ onTouchCancelCapture: true })
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchEnd: true }),
captured: keyOf({ onTouchEndCapture: true })
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchMove: true }),
captured: keyOf({ onTouchMoveCapture: true })
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchStart: true }),
captured: keyOf({ onTouchStartCapture: true })
}
},
volumeChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onVolumeChange: true }),
captured: keyOf({ onVolumeChangeCapture: true })
}
},
waiting: {
phasedRegistrationNames: {
bubbled: keyOf({ onWaiting: true }),
captured: keyOf({ onWaitingCapture: true })
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({ onWheel: true }),
captured: keyOf({ onWheelCapture: true })
}
}
};
var topLevelEventsToDispatchConfig = {
topAbort: eventTypes.abort,
topBlur: eventTypes.blur,
topCanPlay: eventTypes.canPlay,
topCanPlayThrough: eventTypes.canPlayThrough,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topDurationChange: eventTypes.durationChange,
topEmptied: eventTypes.emptied,
topEncrypted: eventTypes.encrypted,
topEnded: eventTypes.ended,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topLoadedData: eventTypes.loadedData,
topLoadedMetadata: eventTypes.loadedMetadata,
topLoadStart: eventTypes.loadStart,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topPause: eventTypes.pause,
topPlay: eventTypes.play,
topPlaying: eventTypes.playing,
topProgress: eventTypes.progress,
topRateChange: eventTypes.rateChange,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSeeked: eventTypes.seeked,
topSeeking: eventTypes.seeking,
topStalled: eventTypes.stalled,
topSubmit: eventTypes.submit,
topSuspend: eventTypes.suspend,
topTimeUpdate: eventTypes.timeUpdate,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topVolumeChange: eventTypes.volumeChange,
topWaiting: eventTypes.waiting,
topWheel: eventTypes.wheel
};
for (var type in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[type].dependencies = [type];
}
var ON_CLICK_KEY = keyOf({ onClick: null });
var onClickListeners = {};
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topAbort:
case topLevelTypes.topCanPlay:
case topLevelTypes.topCanPlayThrough:
case topLevelTypes.topDurationChange:
case topLevelTypes.topEmptied:
case topLevelTypes.topEncrypted:
case topLevelTypes.topEnded:
case topLevelTypes.topError:
case topLevelTypes.topInput:
case topLevelTypes.topLoad:
case topLevelTypes.topLoadedData:
case topLevelTypes.topLoadedMetadata:
case topLevelTypes.topLoadStart:
case topLevelTypes.topPause:
case topLevelTypes.topPlay:
case topLevelTypes.topPlaying:
case topLevelTypes.topProgress:
case topLevelTypes.topRateChange:
case topLevelTypes.topReset:
case topLevelTypes.topSeeked:
case topLevelTypes.topSeeking:
case topLevelTypes.topStalled:
case topLevelTypes.topSubmit:
case topLevelTypes.topSuspend:
case topLevelTypes.topTimeUpdate:
case topLevelTypes.topVolumeChange:
case topLevelTypes.topWaiting:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// FireFox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return null;
}
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
!EventConstructor ? "development" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined;
var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
},
didPutListener: function (id, registrationName, listener) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
if (registrationName === ON_CLICK_KEY) {
var node = ReactMount.getNode(id);
if (!onClickListeners[id]) {
onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction);
}
}
},
willDeleteListener: function (id, registrationName) {
if (registrationName === ON_CLICK_KEY) {
onClickListeners[id].remove();
delete onClickListeners[id];
}
}
};
module.exports = SimpleEventPlugin;
},{"111":111,"129":129,"136":136,"144":144,"148":148,"15":15,"19":19,"65":65,"89":89,"91":91,"92":92,"93":93,"95":95,"96":96,"97":97,"98":98,"99":99}],89:[function(_dereq_,module,exports){
/**
* 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 SyntheticClipboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(92);
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"92":92}],90:[function(_dereq_,module,exports){
/**
* 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 SyntheticCompositionEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(92);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
module.exports = SyntheticCompositionEvent;
},{"92":92}],91:[function(_dereq_,module,exports){
/**
* 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 SyntheticDragEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = _dereq_(96);
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
},{"96":96}],92:[function(_dereq_,module,exports){
/**
* 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 SyntheticEvent
* @typechecks static-only
*/
'use strict';
var PooledClass = _dereq_(24);
var assign = _dereq_(23);
var emptyFunction = _dereq_(136);
var warning = _dereq_(155);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
*/
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
}
assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if ("development" !== 'production') {
"development" !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
}
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if ("development" !== 'production') {
"development" !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
}
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
this[propName] = null;
}
this.dispatchConfig = null;
this.dispatchMarker = null;
this.nativeEvent = null;
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function (Class, Interface) {
var Super = this;
var prototype = Object.create(Super.prototype);
assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = assign({}, Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
module.exports = SyntheticEvent;
},{"136":136,"155":155,"23":23,"24":24}],93:[function(_dereq_,module,exports){
/**
* 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 SyntheticFocusEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(98);
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"98":98}],94:[function(_dereq_,module,exports){
/**
* 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 SyntheticInputEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(92);
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
module.exports = SyntheticInputEvent;
},{"92":92}],95:[function(_dereq_,module,exports){
/**
* 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 SyntheticKeyboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(98);
var getEventCharCode = _dereq_(111);
var getEventKey = _dereq_(112);
var getEventModifierState = _dereq_(113);
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function (event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"111":111,"112":112,"113":113,"98":98}],96:[function(_dereq_,module,exports){
/**
* 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 SyntheticMouseEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(98);
var ViewportMetrics = _dereq_(101);
var getEventModifierState = _dereq_(113);
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function (event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function (event) {
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
},
// "Proprietary" Interface.
pageX: function (event) {
return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function (event) {
return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"101":101,"113":113,"98":98}],97:[function(_dereq_,module,exports){
/**
* 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 SyntheticTouchEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = _dereq_(98);
var getEventModifierState = _dereq_(113);
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"113":113,"98":98}],98:[function(_dereq_,module,exports){
/**
* 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 SyntheticUIEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = _dereq_(92);
var getEventTarget = _dereq_(114);
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: function (event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target != null && target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function (event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"114":114,"92":92}],99:[function(_dereq_,module,exports){
/**
* 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 SyntheticWheelEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = _dereq_(96);
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
},
deltaY: function (event) {
return 'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0;
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"96":96}],100:[function(_dereq_,module,exports){
/**
* 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 = _dereq_(144);
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be run while it is already being run. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM updates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function () {
this.transactionWrappers = this.getTransactionWrappers();
if (this.wrapperInitData) {
this.wrapperInitData.length = 0;
} else {
this.wrapperInitData = [];
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function () {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked. The optional arguments helps prevent the need
* to bind in many cases.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} a Argument to pass to the method.
* @param {Object?=} b Argument to pass to the method.
* @param {Object?=} c Argument to pass to the method.
* @param {Object?=} d Argument to pass to the method.
* @param {Object?=} e Argument to pass to the method.
* @param {Object?=} f Argument to pass to the method.
*
* @return {*} Return value from `method`.
*/
perform: function (method, scope, a, b, c, d, e, f) {
!!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined;
var errorThrown;
var ret;
try {
this._isInTransaction = true;
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// one of these calls threw.
errorThrown = true;
this.initializeAll(0);
ret = method.call(scope, a, b, c, d, e, f);
errorThrown = false;
} finally {
try {
if (errorThrown) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
try {
this.closeAll(0);
} catch (err) {}
} else {
// Since `method` didn't throw, we don't want to silence the exception
// here.
this.closeAll(0);
}
} finally {
this._isInTransaction = false;
}
}
return ret;
},
initializeAll: function (startIndex) {
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
// The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function (startIndex) {
!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined;
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var initData = this.wrapperInitData[i];
var errorThrown;
try {
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// wrapper.close threw.
errorThrown = true;
if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
wrapper.close.call(this, initData);
}
errorThrown = false;
} finally {
if (errorThrown) {
// The closer for wrapper i threw an error; close the remaining
// wrappers but silence any exceptions from them to ensure that the
// first error is the one to bubble up.
try {
this.closeAll(i + 1);
} catch (e) {}
}
}
}
this.wrapperInitData.length = 0;
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occurred.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
},{"144":144}],101:[function(_dereq_,module,exports){
/**
* 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 ViewportMetrics
*/
'use strict';
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function (scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
},{}],102:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule accumulateInto
*/
'use strict';
var invariant = _dereq_(144);
/**
*
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
!(next != null) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined;
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current);
var nextIsArray = Array.isArray(next);
if (currentIsArray && nextIsArray) {
current.push.apply(current, next);
return current;
}
if (currentIsArray) {
current.push(next);
return current;
}
if (nextIsArray) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
},{"144":144}],103:[function(_dereq_,module,exports){
/**
* 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 adler32
*/
'use strict';
var MOD = 65521;
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
var a = 1;
var b = 0;
var i = 0;
var l = data.length;
var m = l & ~0x3;
while (i < m) {
for (; i < Math.min(i + 4096, m); i += 4) {
b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
}
a %= MOD;
b %= MOD;
}
for (; i < l; i++) {
b += a += data.charCodeAt(i);
}
a %= MOD;
b %= MOD;
return a | b << 16;
}
module.exports = adler32;
},{}],104:[function(_dereq_,module,exports){
/**
* 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 canDefineProperty
*/
'use strict';
var canDefineProperty = false;
if ("development" !== 'production') {
try {
Object.defineProperty({}, 'x', { get: function () {} });
canDefineProperty = true;
} catch (x) {
// IE will fail on defineProperty
}
}
module.exports = canDefineProperty;
},{}],105:[function(_dereq_,module,exports){
/**
* 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 dangerousStyleValue
* @typechecks static-only
*/
'use strict';
var CSSProperty = _dereq_(4);
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
},{"4":4}],106:[function(_dereq_,module,exports){
/**
* 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 deprecated
*/
'use strict';
var assign = _dereq_(23);
var warning = _dereq_(155);
/**
* This will log a single deprecation notice per function and forward the call
* on to the new API.
*
* @param {string} fnName The name of the function
* @param {string} newModule The module that fn will exist in
* @param {string} newPackage The module that fn will exist in
* @param {*} ctx The context this forwarded call should run in
* @param {function} fn The function to forward on to
* @return {function} The function that will warn once and then call fn
*/
function deprecated(fnName, newModule, newPackage, ctx, fn) {
var warned = false;
if ("development" !== 'production') {
var newFn = function () {
"development" !== 'production' ? warning(warned,
// Require examples in this string must be split to prevent React's
// build tools from mistaking them for real requires.
// Otherwise the build tools will attempt to build a '%s' module.
'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined;
warned = true;
return fn.apply(ctx, arguments);
};
// We need to make sure all properties of the original fn are copied over.
// In particular, this is needed to support PropTypes
return assign(newFn, fn);
}
return fn;
}
module.exports = deprecated;
},{"155":155,"23":23}],107:[function(_dereq_,module,exports){
/**
* 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 escapeTextContentForBrowser
*/
'use strict';
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'\'': '''
};
var ESCAPE_REGEX = /[&><"']/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextContentForBrowser;
},{}],108:[function(_dereq_,module,exports){
/**
* 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 findDOMNode
* @typechecks static-only
*/
'use strict';
var ReactCurrentOwner = _dereq_(34);
var ReactInstanceMap = _dereq_(62);
var ReactMount = _dereq_(65);
var invariant = _dereq_(144);
var warning = _dereq_(155);
/**
* Returns the DOM node rendered by this element.
*
* @param {ReactComponent|DOMElement} componentOrElement
* @return {?DOMElement} The root node of this element.
*/
function findDOMNode(componentOrElement) {
if ("development" !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
"development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
if (ReactInstanceMap.has(componentOrElement)) {
return ReactMount.getNodeFromInstance(componentOrElement);
}
!(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined;
!false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined;
}
module.exports = findDOMNode;
},{"144":144,"155":155,"34":34,"62":62,"65":65}],109:[function(_dereq_,module,exports){
/**
* 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 flattenChildren
*/
'use strict';
var traverseAllChildren = _dereq_(127);
var warning = _dereq_(155);
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
var keyUnique = result[name] === undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (keyUnique && child != null) {
result[name] = child;
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children == null) {
return children;
}
var result = {};
traverseAllChildren(children, flattenSingleChildIntoContext, result);
return result;
}
module.exports = flattenChildren;
},{"127":127,"155":155}],110:[function(_dereq_,module,exports){
/**
* 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 forEachAccumulated
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function (arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
};
module.exports = forEachAccumulated;
},{}],111:[function(_dereq_,module,exports){
/**
* 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 getEventCharCode
* @typechecks static-only
*/
'use strict';
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
}
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
module.exports = getEventCharCode;
},{}],112:[function(_dereq_,module,exports){
/**
* 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 getEventKey
* @typechecks static-only
*/
'use strict';
var getEventCharCode = _dereq_(111);
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
224: 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
module.exports = getEventKey;
},{"111":111}],113:[function(_dereq_,module,exports){
/**
* 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 getEventModifierState
* @typechecks static-only
*/
'use strict';
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
},{}],114:[function(_dereq_,module,exports){
/**
* 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 getEventTarget
* @typechecks static-only
*/
'use strict';
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
},{}],115:[function(_dereq_,module,exports){
/**
* 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 getIteratorFn
* @typechecks static-only
*/
'use strict';
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
module.exports = getIteratorFn;
},{}],116:[function(_dereq_,module,exports){
/**
* 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 getNodeForCharacterOffset
*/
'use strict';
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
},{}],117:[function(_dereq_,module,exports){
/**
* 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 getTextContentAccessor
*/
'use strict';
var ExecutionEnvironment = _dereq_(130);
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"130":130}],118:[function(_dereq_,module,exports){
/**
* 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 instantiateReactComponent
* @typechecks static-only
*/
'use strict';
var ReactCompositeComponent = _dereq_(33);
var ReactEmptyComponent = _dereq_(54);
var ReactNativeComponent = _dereq_(68);
var assign = _dereq_(23);
var invariant = _dereq_(144);
var warning = _dereq_(155);
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function () {};
assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
_instantiateReactComponent: instantiateReactComponent
});
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
}
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node) {
var instance;
if (node === null || node === false) {
instance = new ReactEmptyComponent(instantiateReactComponent);
} else if (typeof node === 'object') {
var element = node;
!(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined;
// Special case string values
if (typeof element.type === 'string') {
instance = ReactNativeComponent.createInternalComponent(element);
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// representations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
} else {
instance = new ReactCompositeComponentWrapper();
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactNativeComponent.createInstanceForText(node);
} else {
!false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined;
}
if ("development" !== 'production') {
"development" !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined;
}
// Sets up the instance. This can probably just move into the constructor now.
instance.construct(node);
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if ("development" !== 'production') {
instance._isOwnerNecessary = false;
instance._warnedAboutRefsInRender = false;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if ("development" !== 'production') {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
module.exports = instantiateReactComponent;
},{"144":144,"155":155,"23":23,"33":33,"54":54,"68":68}],119:[function(_dereq_,module,exports){
/**
* 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 isEventSupported
*/
'use strict';
var ExecutionEnvironment = _dereq_(130);
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature = document.implementation && document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = (eventName in document);
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
},{"130":130}],120:[function(_dereq_,module,exports){
/**
* 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 isTextInputElement
*/
'use strict';
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea');
}
module.exports = isTextInputElement;
},{}],121:[function(_dereq_,module,exports){
/**
* 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 onlyChild
*/
'use strict';
var ReactElement = _dereq_(52);
var invariant = _dereq_(144);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection. The current implementation of this
* function assumes that a single child gets passed without a wrapper, but the
* purpose of this helper function is to abstract away the particular structure
* of children.
*
* @param {?object} children Child collection structure.
* @return {ReactComponent} The first and only `ReactComponent` contained in the
* structure.
*/
function onlyChild(children) {
!ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined;
return children;
}
module.exports = onlyChild;
},{"144":144,"52":52}],122:[function(_dereq_,module,exports){
/**
* 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 quoteAttributeValueForBrowser
*/
'use strict';
var escapeTextContentForBrowser = _dereq_(107);
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
module.exports = quoteAttributeValueForBrowser;
},{"107":107}],123:[function(_dereq_,module,exports){
/**
* 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 renderSubtreeIntoContainer
*/
'use strict';
var ReactMount = _dereq_(65);
module.exports = ReactMount.renderSubtreeIntoContainer;
},{"65":65}],124:[function(_dereq_,module,exports){
/**
* 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 setInnerHTML
*/
/* globals MSApp */
'use strict';
var ExecutionEnvironment = _dereq_(130);
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = function (node, html) {
node.innerHTML = html;
};
// Win8 apps: Allow all html to be inserted
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
setInnerHTML = function (node, html) {
MSApp.execUnsafeLocalFunction(function () {
node.innerHTML = html;
});
};
}
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function (node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
// in hopes that this is preserved even if "\uFEFF" is transformed to
// the actual Unicode character (by Babel, for example).
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
node.innerHTML = String.fromCharCode(0xFEFF) + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
}
module.exports = setInnerHTML;
},{"130":130}],125:[function(_dereq_,module,exports){
/**
* 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 setTextContent
*/
'use strict';
var ExecutionEnvironment = _dereq_(130);
var escapeTextContentForBrowser = _dereq_(107);
var setInnerHTML = _dereq_(124);
/**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function (node, text) {
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function (node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
},{"107":107,"124":124,"130":130}],126:[function(_dereq_,module,exports){
/**
* 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 shouldUpdateReactComponent
* @typechecks static-only
*/
'use strict';
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
if (prevEmpty || nextEmpty) {
return prevEmpty === nextEmpty;
}
var prevType = typeof prevElement;
var nextType = typeof nextElement;
if (prevType === 'string' || prevType === 'number') {
return nextType === 'string' || nextType === 'number';
} else {
return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
return false;
}
module.exports = shouldUpdateReactComponent;
},{}],127:[function(_dereq_,module,exports){
/**
* 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 traverseAllChildren
*/
'use strict';
var ReactCurrentOwner = _dereq_(34);
var ReactElement = _dereq_(52);
var ReactInstanceHandles = _dereq_(61);
var getIteratorFn = _dereq_(115);
var invariant = _dereq_(144);
var warning = _dereq_(155);
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
var didWarnAboutMaps = false;
function userProvidedKeyEscaper(match) {
return userProvidedKeyEscaperLookup[match];
}
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
if (component && component.key != null) {
// Explicit key
return wrapUserProvidedKey(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* Escape a component key so that it is safe to use in a reactid.
*
* @param {*} text Component key to be escaped.
* @return {string} An escaped string.
*/
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper);
}
/**
* Wrap a `key` value explicitly provided by the user to distinguish it from
* implicitly-generated keys generated by a component's index in its parent.
*
* @param {string} key Value of a user-provided `key` attribute
* @return {string}
*/
function wrapUserProvidedKey(key) {
return '$' + escapeUserProvidedKey(key);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if ("development" !== 'production') {
"development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if ("development" !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
!false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined;
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
module.exports = traverseAllChildren;
},{"115":115,"144":144,"155":155,"34":34,"52":52,"61":61}],128:[function(_dereq_,module,exports){
/**
* Copyright 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 validateDOMNesting
*/
'use strict';
var assign = _dereq_(23);
var emptyFunction = _dereq_(136);
var warning = _dereq_(155);
var validateDOMNesting = emptyFunction;
if ("development" !== 'production') {
// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject', 'desc', 'title'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags = inScopeTags.concat(['button']);
// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
var emptyAncestorInfo = {
parentTag: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
var updatedAncestorInfo = function (oldInfo, tag, instance) {
var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
var info = { tag: tag, instance: instance };
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
}
// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.parentTag = info;
if (tag === 'form') {
ancestorInfo.formTag = info;
}
if (tag === 'a') {
ancestorInfo.aTagInScope = info;
}
if (tag === 'button') {
ancestorInfo.buttonTagInScope = info;
}
if (tag === 'nobr') {
ancestorInfo.nobrTagInScope = info;
}
if (tag === 'p') {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === 'li') {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === 'dd' || tag === 'dt') {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
/**
* Returns whether
*/
var isTagValidWithParent = function (tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case 'select':
return tag === 'option' || tag === 'optgroup' || tag === '#text';
case 'optgroup':
return tag === 'option' || tag === '#text';
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case 'option':
return tag === '#text';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case 'tr':
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case 'tbody':
case 'thead':
case 'tfoot':
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case 'colgroup':
return tag === 'col' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case 'table':
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case 'head':
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case 'html':
return tag === 'head' || tag === 'body';
}
// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch (tag) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
case 'rp':
case 'rt':
return impliedEndTags.indexOf(parentTag) === -1;
case 'caption':
case 'col':
case 'colgroup':
case 'frame':
case 'head':
case 'tbody':
case 'td':
case 'tfoot':
case 'th':
case 'thead':
case 'tr':
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag == null;
}
return true;
};
/**
* Returns whether
*/
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
switch (tag) {
case 'address':
case 'article':
case 'aside':
case 'blockquote':
case 'center':
case 'details':
case 'dialog':
case 'dir':
case 'div':
case 'dl':
case 'fieldset':
case 'figcaption':
case 'figure':
case 'footer':
case 'header':
case 'hgroup':
case 'main':
case 'menu':
case 'nav':
case 'ol':
case 'p':
case 'section':
case 'summary':
case 'ul':
case 'pre':
case 'listing':
case 'table':
case 'hr':
case 'xmp':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return ancestorInfo.pTagInButtonScope;
case 'form':
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case 'li':
return ancestorInfo.listItemTagAutoclosing;
case 'dd':
case 'dt':
return ancestorInfo.dlItemTagAutoclosing;
case 'button':
return ancestorInfo.buttonTagInScope;
case 'a':
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case 'nobr':
return ancestorInfo.nobrTagInScope;
}
return null;
};
/**
* Given a ReactCompositeComponent instance, return a list of its recursive
* owners, starting at the root and ending with the instance itself.
*/
var findOwnerStack = function (instance) {
if (!instance) {
return [];
}
var stack = [];
/*eslint-disable space-after-keywords */
do {
/*eslint-enable space-after-keywords */
stack.push(instance);
} while (instance = instance._currentElement._owner);
stack.reverse();
return stack;
};
var didWarn = {};
validateDOMNesting = function (childTag, childInstance, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.parentTag;
var parentTag = parentInfo && parentInfo.tag;
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var problematic = invalidParent || invalidAncestor;
if (problematic) {
var ancestorTag = problematic.tag;
var ancestorInstance = problematic.instance;
var childOwner = childInstance && childInstance._currentElement._owner;
var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
var childOwners = findOwnerStack(childOwner);
var ancestorOwners = findOwnerStack(ancestorOwner);
var minStackLen = Math.min(childOwners.length, ancestorOwners.length);
var i;
var deepestCommon = -1;
for (i = 0; i < minStackLen; i++) {
if (childOwners[i] === ancestorOwners[i]) {
deepestCommon = i;
} else {
break;
}
}
var UNKNOWN = '(unknown)';
var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ownerInfo = [].concat(
// If the parent and child instances have a common owner ancestor, start
// with that -- otherwise we just start with the parent's owners.
deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag,
// If we're warning about an invalid (non-parent) ancestry, add '...'
invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > ');
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo;
if (didWarn[warnKey]) {
return;
}
didWarn[warnKey] = true;
if (invalidParent) {
var info = '';
if (ancestorTag === 'table' && childTag === 'tr') {
info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
}
"development" !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined;
} else {
"development" !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined;
}
}
};
validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2);
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
// For testing
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.parentTag;
var parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
},{"136":136,"155":155,"23":23}],129:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventListener
* @typechecks
*/
'use strict';
var emptyFunction = _dereq_(136);
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function () {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function () {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function () {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if ("development" !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function () {}
};
module.exports = EventListener;
},{"136":136}],130:[function(_dereq_,module,exports){
/**
* 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 ExecutionEnvironment
*/
'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;
},{}],131:[function(_dereq_,module,exports){
/**
* 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 camelize
* @typechecks
*/
"use strict";
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
},{}],132:[function(_dereq_,module,exports){
/**
* 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 camelizeStyleName
* @typechecks
*/
'use strict';
var camelize = _dereq_(131);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
},{"131":131}],133:[function(_dereq_,module,exports){
/**
* 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 containsNode
* @typechecks
*/
'use strict';
var isTextNode = _dereq_(146);
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function containsNode(_x, _x2) {
var _again = true;
_function: while (_again) {
var outerNode = _x,
innerNode = _x2;
_again = false;
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
_x = outerNode;
_x2 = innerNode.parentNode;
_again = true;
continue _function;
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
}
module.exports = containsNode;
},{"146":146}],134:[function(_dereq_,module,exports){
/**
* 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 createArrayFromMixed
* @typechecks
*/
'use strict';
var toArray = _dereq_(154);
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return(
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
},{"154":154}],135:[function(_dereq_,module,exports){
/**
* 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 createNodesFromMarkup
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
'use strict';
var ExecutionEnvironment = _dereq_(130);
var createArrayFromMixed = _dereq_(134);
var getMarkupWrap = _dereq_(140);
var invariant = _dereq_(144);
/**
* Dummy container used to render all markup.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
!!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined;
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
!handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined;
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = createArrayFromMixed(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"130":130,"134":134,"140":140,"144":144}],136:[function(_dereq_,module,exports){
/**
* 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 emptyFunction
*/
"use strict";
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;
},{}],137:[function(_dereq_,module,exports){
/**
* 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 emptyObject
*/
'use strict';
var emptyObject = {};
if ("development" !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],138:[function(_dereq_,module,exports){
/**
* 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 focusNode
*/
'use strict';
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
},{}],139:[function(_dereq_,module,exports){
/**
* 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 getActiveElement
* @typechecks
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*/
'use strict';
function getActiveElement() /*?DOMElement*/{
if (typeof document === 'undefined') {
return null;
}
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
},{}],140:[function(_dereq_,module,exports){
/**
* 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 getMarkupWrap
*/
/*eslint-disable fb-www/unsafe-html */
'use strict';
var ExecutionEnvironment = _dereq_(130);
var invariant = _dereq_(144);
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap
};
// Initialize the SVG elements since we know they'll always need to be wrapped
// consistently. If they are created inside a <div> they will be initialized in
// the wrong namespace (and will not display).
var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan'];
svgElements.forEach(function (nodeName) {
markupWrap[nodeName] = svgWrap;
shouldWrap[nodeName] = true;
});
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
!!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined;
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
},{"130":130,"144":144}],141:[function(_dereq_,module,exports){
/**
* 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 getUnboundedScrollPosition
* @typechecks
*/
'use strict';
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
},{}],142:[function(_dereq_,module,exports){
/**
* 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 hyphenate
* @typechecks
*/
'use strict';
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],143:[function(_dereq_,module,exports){
/**
* 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 hyphenateStyleName
* @typechecks
*/
'use strict';
var hyphenate = _dereq_(142);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
},{"142":142}],144:[function(_dereq_,module,exports){
/**
* 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 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.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if ("development" !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
},{}],145:[function(_dereq_,module,exports){
/**
* 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 isNode
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
'use strict';
function isNode(object) {
return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
}
module.exports = isNode;
},{}],146:[function(_dereq_,module,exports){
/**
* 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 isTextNode
* @typechecks
*/
'use strict';
var isNode = _dereq_(145);
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
},{"145":145}],147:[function(_dereq_,module,exports){
/**
* 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 keyMirror
* @typechecks static-only
*/
'use strict';
var invariant = _dereq_(144);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function (obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"144":144}],148:[function(_dereq_,module,exports){
/**
* 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 keyOf
*/
/**
* 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.
*/
"use strict";
var keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
},{}],149:[function(_dereq_,module,exports){
/**
* 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 mapObject
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Executes the provided `callback` once for each enumerable own property in the
* object and constructs a new object from the results. The `callback` is
* invoked with three arguments:
*
* - the property value
* - the property name
* - the object being traversed
*
* Properties that are added after the call to `mapObject` will not be visited
* by `callback`. If the values of existing properties are changed, the value
* passed to `callback` will be the value at the time `mapObject` visits them.
* Properties that are deleted before being visited are not visited.
*
* @grep function objectMap()
* @grep function objMap()
*
* @param {?object} object
* @param {function} callback
* @param {*} context
* @return {?object}
*/
function mapObject(object, callback, context) {
if (!object) {
return null;
}
var result = {};
for (var name in object) {
if (hasOwnProperty.call(object, name)) {
result[name] = callback.call(context, object[name], name, object);
}
}
return result;
}
module.exports = mapObject;
},{}],150:[function(_dereq_,module,exports){
/**
* 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 memoizeStringOnly
* @typechecks static-only
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
},{}],151:[function(_dereq_,module,exports){
/**
* 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 performance
* @typechecks
*/
'use strict';
var ExecutionEnvironment = _dereq_(130);
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.msPerformance || window.webkitPerformance;
}
module.exports = performance || {};
},{"130":130}],152:[function(_dereq_,module,exports){
/**
* 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 performanceNow
* @typechecks
*/
'use strict';
var performance = _dereq_(151);
var performanceNow;
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (performance.now) {
performanceNow = function () {
return performance.now();
};
} else {
performanceNow = function () {
return Date.now();
};
}
module.exports = performanceNow;
},{"151":151}],153:[function(_dereq_,module,exports){
/**
* 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 shallowEqual
* @typechecks
*
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var bHasOwnProperty = hasOwnProperty.bind(objB);
for (var i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],154:[function(_dereq_,module,exports){
/**
* 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 toArray
* @typechecks
*/
'use strict';
var invariant = _dereq_(144);
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
// old versions of Safari).
!(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined;
!(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined;
!(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined;
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
module.exports = toArray;
},{"144":144}],155:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule warning
*/
'use strict';
var emptyFunction = _dereq_(136);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("development" !== 'production') {
warning = function (condition, format) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
}
};
}
module.exports = warning;
},{"136":136}]},{},[1])(1)
}); |
src/svg-icons/image/tune.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTune = (props) => (
<SvgIcon {...props}>
<path d="M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z"/>
</SvgIcon>
);
ImageTune = pure(ImageTune);
ImageTune.displayName = 'ImageTune';
ImageTune.muiName = 'SvgIcon';
export default ImageTune;
|
imports/plugins/core/email/client/containers/emailLogs.js | together-web-pj/together-web-pj | import { useDeps } from "react-simple-di";
import { Meteor } from "meteor/meteor";
import actions from "../actions";
import EmailLogs from "../components/emailLogs";
import { Loading } from "/imports/plugins/core/ui/client/components";
import { Jobs } from "/lib/collections";
import { composeWithTracker, merge } from "/lib/api/compose";
const composer = ({}, onData) => {
if (Meteor.subscribe("Emails").ready()) {
const emails = Jobs.find().fetch();
onData(null, { emails });
}
};
const depsMapper = () => ({
resend: actions.logs.resend
});
export default merge(
composeWithTracker(composer, Loading),
useDeps(depsMapper)
)(EmailLogs);
|
docs/app/Examples/elements/List/ContentVariations/ListExampleFloated.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Button, Image, List } from 'semantic-ui-react'
const ListExampleFloated = () => (
<List divided verticalAlign='middle'>
<List.Item>
<List.Content floated='right'>
<Button>Add</Button>
</List.Content>
<Image avatar src='/assets/images/avatar/small/lena.png' />
<List.Content>
Lena
</List.Content>
</List.Item>
<List.Item>
<List.Content floated='right'>
<Button>Add</Button>
</List.Content>
<Image avatar src='/assets/images/avatar/small/lindsay.png' />
<List.Content>
Lindsay
</List.Content>
</List.Item>
<List.Item>
<List.Content floated='right'>
<Button>Add</Button>
</List.Content>
<Image avatar src='/assets/images/avatar/small/mark.png' />
<List.Content>
Mark
</List.Content>
</List.Item>
<List.Item>
<List.Content floated='right'>
<Button>Add</Button>
</List.Content>
<Image avatar src='/assets/images/avatar/small/molly.png' />
<List.Content>
Molly
</List.Content>
</List.Item>
</List>
)
export default ListExampleFloated
|
blueocean-material-icons/src/js/components/svg-icons/content/report.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ContentReport = (props) => (
<SvgIcon {...props}>
<path d="M15.73 3H8.27L3 8.27v7.46L8.27 21h7.46L21 15.73V8.27L15.73 3zM12 17.3c-.72 0-1.3-.58-1.3-1.3 0-.72.58-1.3 1.3-1.3.72 0 1.3.58 1.3 1.3 0 .72-.58 1.3-1.3 1.3zm1-4.3h-2V7h2v6z"/>
</SvgIcon>
);
ContentReport.displayName = 'ContentReport';
ContentReport.muiName = 'SvgIcon';
export default ContentReport;
|
src/components/includes/header/logo.js | meherranjan/aerosailor | import React from 'react'
import aerosailorIcon from '../../../../static/logo-icon.svg'
import aerosailorText from '../../../../static/logo-text.svg'
const Logo = () => (
<div className="logo-container">
<h1 className="masthead-title">
<a className="brand" href="/" title="Aerosailor">
<img className="for-desktop" src={aerosailorIcon} alt="Aerosailor Logo" />
<img className="for-mobile" src={aerosailorText} alt="Aerosailor Logo" />
</a>
</h1>
</div>
)
export default Logo
|
src/svg-icons/av/av-timer.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvAvTimer = (props) => (
<SvgIcon {...props}>
<path d="M11 17c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1zm0-14v4h2V5.08c3.39.49 6 3.39 6 6.92 0 3.87-3.13 7-7 7s-7-3.13-7-7c0-1.68.59-3.22 1.58-4.42L12 13l1.41-1.41-6.8-6.8v.02C4.42 6.45 3 9.05 3 12c0 4.97 4.02 9 9 9 4.97 0 9-4.03 9-9s-4.03-9-9-9h-1zm7 9c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zM6 12c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1z"/>
</SvgIcon>
);
AvAvTimer = pure(AvAvTimer);
AvAvTimer.displayName = 'AvAvTimer';
export default AvAvTimer;
|
packages/material-ui-icons/src/DeveloperBoard.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z" /><path fill="none" d="M0 0h24v24H0zm0 0h24v24H0z" /></React.Fragment>
, 'DeveloperBoard');
|
app/js/components/type/damageClass.component.js | milk-shake/electron-pokemon | import React from 'react';
import ReactDOM from 'react-dom';
export default class DamageClassComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return <span className={"damage-class damage-class--" + this.props.type.name.toLowerCase()}>{this.props.type.name}</span>
}
}
|
src/components/layer/layer.js | miaoji/guojibackend | import { Modal, message } from 'antd'
import React from 'react'
import ReactDOM from 'react-dom'
import classnames from 'classnames'
import styles from './layer.less'
const { info, success, error, warning, confirm } = Modal
const layer = {
prefixCls: 'ant-layer',
index: 1,
info,
success,
error,
warning,
confirm,
}
layer.close = (index) => new Promise((resolve, reject) => {
const { prefixCls } = layer
let div = document.getElementById(`${prefixCls}-reference-${index}`)
if (index === undefined) {
const references = document.querySelectorAll(`.${prefixCls}-reference`)
div = references[references.length - 1]
}
if (!div) {
message.error('关闭失败,未找到Dom')
return
}
const unmountResult = ReactDOM.unmountComponentAtNode(div)
if (unmountResult && div.parentNode) {
div.parentNode.removeChild(div)
resolve(index)
} else {
reject(index)
}
})
layer.closeAll = () => {
const { prefixCls } = layer
const references = document.querySelectorAll(`.${prefixCls}-reference`)
let i = 0
while (i < references.length) {
layer.close()
i++
}
}
layer.open = (config) => {
const props = Object.assign({}, config)
const { content, ...modalProps } = props
const { className, wrapClassName = '', verticalCenter = true } = modalProps
const { prefixCls } = layer
const index = layer.index++
let div = document.createElement('div')
div.id = `${prefixCls}-reference-${index}`
div.className = `${prefixCls}-reference`
document.body.appendChild(div)
ReactDOM.render(
<Modal
visible
title="Title"
transitionName="zoom"
maskTransitionName="fade"
onCancel={() => {
layer.close(index)
}}
onOk={() => {
layer.close(index)
}}
{...modalProps}
wrapClassName={classnames({ [styles.verticalCenter]: verticalCenter, [wrapClassName]: true })}
className={classnames(prefixCls, className, [`${prefixCls}-${index}`])}
>
<div className={`${prefixCls}-body-wrapper`} style={{ maxHeight: document.body.clientHeight - 256 }}>
{content}
</div>
</Modal>, div)
return index
}
export default layer
|
ajax/libs/ember-data.js/2.15.0-beta.1/ember-data.js | pvnr0082t/cdnjs | (function(){
"use strict";
/*!
* @overview Ember Data
* @copyright Copyright 2011-2017 Tilde Inc. and contributors.
* Portions Copyright 2011 LivingSocial Inc.
* @license Licensed under MIT license (see license.js)
* @version 2.15.0-beta.1
*/
var loader, define, requireModule, require, requirejs;
(function (global) {
'use strict';
var heimdall = global.heimdall;
function dict() {
var obj = Object.create(null);
obj['__'] = undefined;
delete obj['__'];
return obj;
}
// Save off the original values of these globals, so we can restore them if someone asks us to
var oldGlobals = {
loader: loader,
define: define,
requireModule: requireModule,
require: require,
requirejs: requirejs
};
requirejs = require = requireModule = function (id) {
var pending = [];
var mod = findModule(id, '(require)', pending);
for (var i = pending.length - 1; i >= 0; i--) {
pending[i].exports();
}
return mod.module.exports;
};
loader = {
noConflict: function (aliases) {
var oldName, newName;
for (oldName in aliases) {
if (aliases.hasOwnProperty(oldName)) {
if (oldGlobals.hasOwnProperty(oldName)) {
newName = aliases[oldName];
global[newName] = global[oldName];
global[oldName] = oldGlobals[oldName];
}
}
}
}
};
var registry = dict();
var seen = dict();
var uuid = 0;
function unsupportedModule(length) {
throw new Error('an unsupported module was defined, expected `define(id, deps, module)` instead got: `' + length + '` arguments to define`');
}
var defaultDeps = ['require', 'exports', 'module'];
function Module(id, deps, callback, alias) {
this.uuid = uuid++;
this.id = id;
this.deps = !deps.length && callback.length ? defaultDeps : deps;
this.module = { exports: {} };
this.callback = callback;
this.hasExportsAsDep = false;
this.isAlias = alias;
this.reified = new Array(deps.length);
/*
Each module normally passes through these states, in order:
new : initial state
pending : this module is scheduled to be executed
reifying : this module's dependencies are being executed
reified : this module's dependencies finished executing successfully
errored : this module's dependencies failed to execute
finalized : this module executed successfully
*/
this.state = 'new';
}
Module.prototype.makeDefaultExport = function () {
var exports = this.module.exports;
if (exports !== null && (typeof exports === 'object' || typeof exports === 'function') && exports['default'] === undefined && Object.isExtensible(exports)) {
exports['default'] = exports;
}
};
Module.prototype.exports = function () {
// if finalized, there is no work to do. If reifying, there is a
// circular dependency so we must return our (partial) exports.
if (this.state === 'finalized' || this.state === 'reifying') {
return this.module.exports;
}
if (loader.wrapModules) {
this.callback = loader.wrapModules(this.id, this.callback);
}
this.reify();
var result = this.callback.apply(this, this.reified);
this.reified.length = 0;
this.state = 'finalized';
if (!(this.hasExportsAsDep && result === undefined)) {
this.module.exports = result;
}
this.makeDefaultExport();
return this.module.exports;
};
Module.prototype.unsee = function () {
this.state = 'new';
this.module = { exports: {} };
};
Module.prototype.reify = function () {
if (this.state === 'reified') {
return;
}
this.state = 'reifying';
try {
this.reified = this._reify();
this.state = 'reified';
} finally {
if (this.state === 'reifying') {
this.state = 'errored';
}
}
};
Module.prototype._reify = function () {
var reified = this.reified.slice();
for (var i = 0; i < reified.length; i++) {
var mod = reified[i];
reified[i] = mod.exports ? mod.exports : mod.module.exports();
}
return reified;
};
Module.prototype.findDeps = function (pending) {
if (this.state !== 'new') {
return;
}
this.state = 'pending';
var deps = this.deps;
for (var i = 0; i < deps.length; i++) {
var dep = deps[i];
var entry = this.reified[i] = { exports: undefined, module: undefined };
if (dep === 'exports') {
this.hasExportsAsDep = true;
entry.exports = this.module.exports;
} else if (dep === 'require') {
entry.exports = this.makeRequire();
} else if (dep === 'module') {
entry.exports = this.module;
} else {
entry.module = findModule(resolve(dep, this.id), this.id, pending);
}
}
};
Module.prototype.makeRequire = function () {
var id = this.id;
var r = function (dep) {
return require(resolve(dep, id));
};
r['default'] = r;
r.moduleId = id;
r.has = function (dep) {
return has(resolve(dep, id));
};
return r;
};
define = function (id, deps, callback) {
var module = registry[id];
// If a module for this id has already been defined and is in any state
// other than `new` (meaning it has been or is currently being required),
// then we return early to avoid redefinition.
if (module && module.state !== 'new') {
return;
}
if (arguments.length < 2) {
unsupportedModule(arguments.length);
}
if (!Array.isArray(deps)) {
callback = deps;
deps = [];
}
if (callback instanceof Alias) {
registry[id] = new Module(callback.id, deps, callback, true);
} else {
registry[id] = new Module(id, deps, callback, false);
}
};
define.exports = function (name, defaultExport) {
var module = registry[name];
// If a module for this name has already been defined and is in any state
// other than `new` (meaning it has been or is currently being required),
// then we return early to avoid redefinition.
if (module && module.state !== 'new') {
return;
}
module = new Module(name, [], noop, null);
module.module.exports = defaultExport;
module.state = 'finalized';
registry[name] = module;
return module;
};
function noop() {}
// we don't support all of AMD
// define.amd = {};
function Alias(id) {
this.id = id;
}
define.alias = function (id, target) {
if (arguments.length === 2) {
return define(target, new Alias(id));
}
return new Alias(id);
};
function missingModule(id, referrer) {
throw new Error('Could not find module `' + id + '` imported from `' + referrer + '`');
}
function findModule(id, referrer, pending) {
var mod = registry[id] || registry[id + '/index'];
while (mod && mod.isAlias) {
mod = registry[mod.id];
}
if (!mod) {
missingModule(id, referrer);
}
if (pending && mod.state !== 'pending' && mod.state !== 'finalized') {
mod.findDeps(pending);
pending.push(mod);
}
return mod;
}
function resolve(child, id) {
if (child.charAt(0) !== '.') {
return child;
}
var parts = child.split('/');
var nameParts = id.split('/');
var parentBase = nameParts.slice(0, -1);
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if (part === '..') {
if (parentBase.length === 0) {
throw new Error('Cannot access parent module of root');
}
parentBase.pop();
} else if (part === '.') {
continue;
} else {
parentBase.push(part);
}
}
return parentBase.join('/');
}
function has(id) {
return !!(registry[id] || registry[id + '/index']);
}
requirejs.entries = requirejs._eak_seen = registry;
requirejs.has = has;
requirejs.unsee = function (id) {
findModule(id, '(unsee)', false).unsee();
};
requirejs.clear = function () {
requirejs.entries = requirejs._eak_seen = registry = dict();
seen = dict();
};
// This code primes the JS engine for good performance by warming the
// JIT compiler for these functions.
define('foo', function () {});
define('foo/bar', [], function () {});
define('foo/asdf', ['module', 'exports', 'require'], function (module, exports, require) {
if (require.has('foo/bar')) {
require('foo/bar');
}
});
define('foo/baz', [], define.alias('foo'));
define('foo/quz', define.alias('foo'));
define.alias('foo', 'foo/qux');
define('foo/bar', ['foo', './quz', './baz', './asdf', './bar', '../foo'], function () {});
define('foo/main', ['foo/bar'], function () {});
define.exports('foo/exports', {});
require('foo/exports');
require('foo/main');
require.unsee('foo/bar');
requirejs.clear();
if (typeof exports === 'object' && typeof module === 'object' && module.exports) {
module.exports = { require: require, define: define };
}
})(this);
define('ember-data/-debug', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.assertPolymorphicType = undefined;
exports.instrument = instrument;
function instrument(method) {
return method();
}
/*
Assert that `addedRecord` has a valid type so it can be added to the
relationship of the `record`.
The assert basically checks if the `addedRecord` can be added to the
relationship (specified via `relationshipMeta`) of the `record`.
This utility should only be used internally, as both record parameters must
be an InternalModel and the `relationshipMeta` needs to be the meta
information about the relationship, retrieved via
`record.relationshipFor(key)`.
@method assertPolymorphicType
@param {InternalModel} internalModel
@param {RelationshipMeta} relationshipMeta retrieved via
`record.relationshipFor(key)`
@param {InternalModel} addedRecord record which
should be added/set for the relationship
*/
var assertPolymorphicType = void 0;
if (false) {
var checkPolymorphic = function checkPolymorphic(modelClass, addedModelClass) {
if (modelClass.__isMixin) {
//TODO Need to do this in order to support mixins, should convert to public api
//once it exists in Ember
return modelClass.__mixin.detect(addedModelClass.PrototypeMixin);
}
if (_ember.default.MODEL_FACTORY_INJECTIONS) {
modelClass = modelClass.superclass;
}
return modelClass.detect(addedModelClass);
};
exports.assertPolymorphicType = assertPolymorphicType = function assertPolymorphicType(parentInternalModel, relationshipMeta, addedInternalModel) {
var addedModelName = addedInternalModel.modelName;
var parentModelName = parentInternalModel.modelName;
var key = relationshipMeta.key;
var relationshipModelName = relationshipMeta.type;
var relationshipClass = parentInternalModel.store.modelFor(relationshipModelName);
var assertionMessage = 'You cannot add a record of modelClass \'' + addedModelName + '\' to the \'' + parentModelName + '.' + key + '\' relationship (only \'' + relationshipModelName + '\' allowed)';
(false && _ember.default.assert(assertionMessage, checkPolymorphic(relationshipClass, addedInternalModel.modelClass)));
};
}
exports.assertPolymorphicType = assertPolymorphicType;
});
define('ember-data/-private/adapters/build-url-mixin', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
var get = _ember.default.get;
/**
WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4
## Using BuildURLMixin
To use url building, include the mixin when extending an adapter, and call `buildURL` where needed.
The default behaviour is designed for RESTAdapter.
### Example
```javascript
export default DS.Adapter.extend(BuildURLMixin, {
findRecord: function(store, type, id, snapshot) {
var url = this.buildURL(type.modelName, id, snapshot, 'findRecord');
return this.ajax(url, 'GET');
}
});
```
### Attributes
The `host` and `namespace` attributes will be used if defined, and are optional.
@class BuildURLMixin
@namespace DS
*/
exports.default = _ember.default.Mixin.create({
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example, 'post'
becomes 'posts' and 'person' becomes 'people'). To override the
pluralization see [pathForType](#method_pathForType).
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
When called by RESTAdapter.findMany() the `id` and `snapshot` parameters
will be arrays of ids and snapshots.
@method buildURL
@param {String} modelName
@param {(String|Array|Object)} id single id or array of ids or query
@param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots
@param {String} requestType
@param {Object} query object of query parameters to send for query requests.
@return {String} url
*/
buildURL: function (modelName, id, snapshot, requestType, query) {
switch (requestType) {
case 'findRecord':
return this.urlForFindRecord(id, modelName, snapshot);
case 'findAll':
return this.urlForFindAll(modelName, snapshot);
case 'query':
return this.urlForQuery(query, modelName);
case 'queryRecord':
return this.urlForQueryRecord(query, modelName);
case 'findMany':
return this.urlForFindMany(id, modelName, snapshot);
case 'findHasMany':
return this.urlForFindHasMany(id, modelName, snapshot);
case 'findBelongsTo':
return this.urlForFindBelongsTo(id, modelName, snapshot);
case 'createRecord':
return this.urlForCreateRecord(modelName, snapshot);
case 'updateRecord':
return this.urlForUpdateRecord(id, modelName, snapshot);
case 'deleteRecord':
return this.urlForDeleteRecord(id, modelName, snapshot);
default:
return this._buildURL(modelName, id);
}
},
/**
@method _buildURL
@private
@param {String} modelName
@param {String} id
@return {String} url
*/
_buildURL: function (modelName, id) {
var path = void 0;
var url = [];
var host = get(this, 'host');
var prefix = this.urlPrefix();
if (modelName) {
path = this.pathForType(modelName);
if (path) {
url.push(path);
}
}
if (id) {
url.push(encodeURIComponent(id));
}
if (prefix) {
url.unshift(prefix);
}
url = url.join('/');
if (!host && url && url.charAt(0) !== '/') {
url = '/' + url;
}
return url;
},
/**
Builds a URL for a `store.findRecord(type, id)` call.
Example:
```app/adapters/user.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
urlForFindRecord(id, modelName, snapshot) {
let baseUrl = this.buildURL();
return `${baseUrl}/users/${snapshot.adapterOptions.user_id}/playlists/${id}`;
}
});
```
@method urlForFindRecord
@param {String} id
@param {String} modelName
@param {DS.Snapshot} snapshot
@return {String} url
*/
urlForFindRecord: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
Builds a URL for a `store.findAll(type)` call.
Example:
```app/adapters/comment.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
urlForFindAll(modelName, snapshot) {
return 'data/comments.json';
}
});
```
@method urlForFindAll
@param {String} modelName
@param {DS.SnapshotRecordArray} snapshot
@return {String} url
*/
urlForFindAll: function (modelName, snapshot) {
return this._buildURL(modelName);
},
/**
Builds a URL for a `store.query(type, query)` call.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.github.com',
urlForQuery (query, modelName) {
switch(modelName) {
case 'repo':
return `https://api.github.com/orgs/${query.orgId}/repos`;
default:
return this._super(...arguments);
}
}
});
```
@method urlForQuery
@param {Object} query
@param {String} modelName
@return {String} url
*/
urlForQuery: function (query, modelName) {
return this._buildURL(modelName);
},
/**
Builds a URL for a `store.queryRecord(type, query)` call.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
urlForQueryRecord({ slug }, modelName) {
let baseUrl = this.buildURL();
return `${baseUrl}/${encodeURIComponent(slug)}`;
}
});
```
@method urlForQueryRecord
@param {Object} query
@param {String} modelName
@return {String} url
*/
urlForQueryRecord: function (query, modelName) {
return this._buildURL(modelName);
},
/**
Builds a URL for coalesceing multiple `store.findRecord(type, id)`
records into 1 request when the adapter's `coalesceFindRequests`
property is true.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
urlForFindMany(ids, modelName) {
let baseUrl = this.buildURL();
return `${baseUrl}/coalesce`;
}
});
```
@method urlForFindMany
@param {Array} ids
@param {String} modelName
@param {Array} snapshots
@return {String} url
*/
urlForFindMany: function (ids, modelName, snapshots) {
return this._buildURL(modelName);
},
/**
Builds a URL for fetching a async hasMany relationship when a url
is not provided by the server.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
urlForFindHasMany(id, modelName, snapshot) {
let baseUrl = this.buildURL(id, modelName);
return `${baseUrl}/relationships`;
}
});
```
@method urlForFindHasMany
@param {String} id
@param {String} modelName
@param {DS.Snapshot} snapshot
@return {String} url
*/
urlForFindHasMany: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
Builds a URL for fetching a async belongsTo relationship when a url
is not provided by the server.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
urlForFindBelongsTo(id, modelName, snapshot) {
let baseUrl = this.buildURL(id, modelName);
return `${baseUrl}/relationships`;
}
});
```
@method urlForFindBelongsTo
@param {String} id
@param {String} modelName
@param {DS.Snapshot} snapshot
@return {String} url
*/
urlForFindBelongsTo: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
Builds a URL for a `record.save()` call when the record was created
locally using `store.createRecord()`.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
urlForCreateRecord(modelName, snapshot) {
return this._super(...arguments) + '/new';
}
});
```
@method urlForCreateRecord
@param {String} modelName
@param {DS.Snapshot} snapshot
@return {String} url
*/
urlForCreateRecord: function (modelName, snapshot) {
return this._buildURL(modelName);
},
/**
Builds a URL for a `record.save()` call when the record has been update locally.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
urlForUpdateRecord(id, modelName, snapshot) {
return `/${id}/feed?access_token=${snapshot.adapterOptions.token}`;
}
});
```
@method urlForUpdateRecord
@param {String} id
@param {String} modelName
@param {DS.Snapshot} snapshot
@return {String} url
*/
urlForUpdateRecord: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
Builds a URL for a `record.save()` call when the record has been deleted locally.
Example:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
urlForDeleteRecord(id, modelName, snapshot) {
return this._super(...arguments) + '/destroy';
}
});
```
@method urlForDeleteRecord
@param {String} id
@param {String} modelName
@param {DS.Snapshot} snapshot
@return {String} url
*/
urlForDeleteRecord: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
@method urlPrefix
@private
@param {String} path
@param {String} parentURL
@return {String} urlPrefix
*/
urlPrefix: function (path, parentURL) {
var host = get(this, 'host');
var namespace = get(this, 'namespace');
if (!host || host === '/') {
host = '';
}
if (path) {
// Protocol relative url
if (/^\/\//.test(path) || /http(s)?:\/\//.test(path)) {
// Do nothing, the full host is already included.
return path;
// Absolute path
} else if (path.charAt(0) === '/') {
return '' + host + path;
// Relative path
} else {
return parentURL + '/' + path;
}
}
// No path provided
var url = [];
if (host) {
url.push(host);
}
if (namespace) {
url.push(namespace);
}
return url.join('/');
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
pathForType: function(modelName) {
var decamelized = Ember.String.decamelize(modelName);
return Ember.String.pluralize(decamelized);
}
});
```
@method pathForType
@param {String} modelName
@return {String} path
**/
pathForType: function (modelName) {
var camelized = _ember.default.String.camelize(modelName);
return _ember.default.String.pluralize(camelized);
}
});
});
define('ember-data/-private/adapters/errors', ['exports', 'ember', 'ember-data/-private/features'], function (exports, _ember, _features) {
'use strict';
exports.__esModule = true;
exports.ServerError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.AbortError = exports.TimeoutError = exports.InvalidError = undefined;
exports.AdapterError = AdapterError;
exports.errorsHashToArray = errorsHashToArray;
exports.errorsArrayToHash = errorsArrayToHash;
var EmberError = _ember.default.Error;
var SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;
var SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/;
var PRIMARY_ATTRIBUTE_KEY = 'base';
/**
A `DS.AdapterError` is used by an adapter to signal that an error occurred
during a request to an external API. It indicates a generic error, and
subclasses are used to indicate specific error states. The following
subclasses are provided:
- `DS.InvalidError`
- `DS.TimeoutError`
- `DS.AbortError`
- `DS.UnauthorizedError`
- `DS.ForbiddenError`
- `DS.NotFoundError`
- `DS.ConflictError`
- `DS.ServerError`
To create a custom error to signal a specific error state in communicating
with an external API, extend the `DS.AdapterError`. For example if the
external API exclusively used HTTP `503 Service Unavailable` to indicate
it was closed for maintenance:
```app/adapters/maintenance-error.js
import DS from 'ember-data';
export default DS.AdapterError.extend({ message: "Down for maintenance." });
```
This error would then be returned by an adapter's `handleResponse` method:
```app/adapters/application.js
import DS from 'ember-data';
import MaintenanceError from './maintenance-error';
export default DS.JSONAPIAdapter.extend({
handleResponse(status) {
if (503 === status) {
return new MaintenanceError();
}
return this._super(...arguments);
}
});
```
And can then be detected in an application and used to send the user to an
`under-maintenance` route:
```app/routes/application.js
import Ember from 'ember';
import MaintenanceError from '../adapters/maintenance-error';
export default Ember.Route.extend({
actions: {
error(error, transition) {
if (error instanceof MaintenanceError) {
this.transitionTo('under-maintenance');
return;
}
// ...other error handling logic
}
}
});
```
@class AdapterError
@namespace DS
*/
function AdapterError(errors) {
var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Adapter operation failed';
this.isAdapterError = true;
EmberError.call(this, message);
this.errors = errors || [{
title: 'Adapter Error',
detail: message
}];
}
var extendedErrorsEnabled = false;
if (true) {
extendedErrorsEnabled = true;
}
function extendFn(ErrorClass) {
return function () {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
defaultMessage = _ref.message;
return extend(ErrorClass, defaultMessage);
};
}
function extend(ParentErrorClass, defaultMessage) {
var ErrorClass = function (errors, message) {
(false && _ember.default.assert('`AdapterError` expects json-api formatted errors array.', Array.isArray(errors || [])));
ParentErrorClass.call(this, errors, message || defaultMessage);
};
ErrorClass.prototype = Object.create(ParentErrorClass.prototype);
if (extendedErrorsEnabled) {
ErrorClass.extend = extendFn(ErrorClass);
}
return ErrorClass;
}
AdapterError.prototype = Object.create(EmberError.prototype);
if (extendedErrorsEnabled) {
AdapterError.extend = extendFn(AdapterError);
}
/**
A `DS.InvalidError` is used by an adapter to signal the external API
was unable to process a request because the content was not
semantically correct or meaningful per the API. Usually this means a
record failed some form of server side validation. When a promise
from an adapter is rejected with a `DS.InvalidError` the record will
transition to the `invalid` state and the errors will be set to the
`errors` property on the record.
For Ember Data to correctly map errors to their corresponding
properties on the model, Ember Data expects each error to be
a valid json-api error object with a `source/pointer` that matches
the property name. For example if you had a Post model that
looked like this.
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('string')
});
```
To show an error from the server related to the `title` and
`content` properties your adapter could return a promise that
rejects with a `DS.InvalidError` object that looks like this:
```app/adapters/post.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
updateRecord() {
// Fictional adapter that always rejects
return Ember.RSVP.reject(new DS.InvalidError([
{
detail: 'Must be unique',
source: { pointer: '/data/attributes/title' }
},
{
detail: 'Must not be blank',
source: { pointer: '/data/attributes/content'}
}
]));
}
});
```
Your backend may use different property names for your records the
store will attempt extract and normalize the errors using the
serializer's `extractErrors` method before the errors get added to
the the model. As a result, it is safe for the `InvalidError` to
wrap the error payload unaltered.
@class InvalidError
@namespace DS
*/
var InvalidError = exports.InvalidError = extend(AdapterError, 'The adapter rejected the commit because it was invalid');
/**
A `DS.TimeoutError` is used by an adapter to signal that a request
to the external API has timed out. I.e. no response was received from
the external API within an allowed time period.
An example use case would be to warn the user to check their internet
connection if an adapter operation has timed out:
```app/routes/application.js
import Ember from 'ember';
import DS from 'ember-data';
const { TimeoutError } = DS;
export default Ember.Route.extend({
actions: {
error(error, transition) {
if (error instanceof TimeoutError) {
// alert the user
alert('Are you still connected to the internet?');
return;
}
// ...other error handling logic
}
}
});
```
@class TimeoutError
@namespace DS
*/
var TimeoutError = exports.TimeoutError = extend(AdapterError, 'The adapter operation timed out');
/**
A `DS.AbortError` is used by an adapter to signal that a request to
the external API was aborted. For example, this can occur if the user
navigates away from the current page after a request to the external API
has been initiated but before a response has been received.
@class AbortError
@namespace DS
*/
var AbortError = exports.AbortError = extend(AdapterError, 'The adapter operation was aborted');
/**
A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response
status. It is used by an adapter to signal that a request to the external
API was rejected because authorization is required and has failed or has not
yet been provided.
An example use case would be to redirect the user to a log in route if a
request is unauthorized:
```app/routes/application.js
import Ember from 'ember';
import DS from 'ember-data';
const { UnauthorizedError } = DS;
export default Ember.Route.extend({
actions: {
error(error, transition) {
if (error instanceof UnauthorizedError) {
// go to the sign in route
this.transitionTo('login');
return;
}
// ...other error handling logic
}
}
});
```
@class UnauthorizedError
@namespace DS
*/
var UnauthorizedError = exports.UnauthorizedError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is unauthorized') : null;
/**
A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status.
It is used by an adapter to signal that a request to the external API was
valid but the server is refusing to respond to it. If authorization was
provided and is valid, then the authenticated user does not have the
necessary permissions for the request.
@class ForbiddenError
@namespace DS
*/
var ForbiddenError = exports.ForbiddenError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is forbidden') : null;
/**
A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status.
It is used by an adapter to signal that a request to the external API
was rejected because the resource could not be found on the API.
An example use case would be to detect if the user has entered a route
for a specific model that does not exist. For example:
```app/routes/post.js
import Ember from 'ember';
import DS from 'ember-data';
const { NotFoundError } = DS;
export default Ember.Route.extend({
model(params) {
return this.get('store').findRecord('post', params.post_id);
},
actions: {
error(error, transition) {
if (error instanceof NotFoundError) {
// redirect to a list of all posts instead
this.transitionTo('posts');
} else {
// otherwise let the error bubble
return true;
}
}
}
});
```
@class NotFoundError
@namespace DS
*/
var NotFoundError = exports.NotFoundError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter could not find the resource') : null;
/**
A `DS.ConflictError` equates to a HTTP `409 Conflict` response status.
It is used by an adapter to indicate that the request could not be processed
because of a conflict in the request. An example scenario would be when
creating a record with a client generated id but that id is already known
to the external API.
@class ConflictError
@namespace DS
*/
var ConflictError = exports.ConflictError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a conflict') : null;
/**
A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response
status. It is used by the adapter to indicate that a request has failed
because of an error in the external API.
@class ServerError
@namespace DS
*/
var ServerError = exports.ServerError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a server error') : null;
/**
Convert an hash of errors into an array with errors in JSON-API format.
```javascript
import DS from 'ember-data';
const { errorsHashToArray } = DS;
let errors = {
base: 'Invalid attributes on saving this record',
name: 'Must be present',
age: ['Must be present', 'Must be a number']
};
let errorsArray = errorsHashToArray(errors);
// [
// {
// title: "Invalid Document",
// detail: "Invalid attributes on saving this record",
// source: { pointer: "/data" }
// },
// {
// title: "Invalid Attribute",
// detail: "Must be present",
// source: { pointer: "/data/attributes/name" }
// },
// {
// title: "Invalid Attribute",
// detail: "Must be present",
// source: { pointer: "/data/attributes/age" }
// },
// {
// title: "Invalid Attribute",
// detail: "Must be a number",
// source: { pointer: "/data/attributes/age" }
// }
// ]
```
@method errorsHashToArray
@public
@namespace
@for DS
@param {Object} errors hash with errors as properties
@return {Array} array of errors in JSON-API format
*/
function errorsHashToArray(errors) {
var out = [];
if (_ember.default.isPresent(errors)) {
Object.keys(errors).forEach(function (key) {
var messages = _ember.default.makeArray(errors[key]);
for (var i = 0; i < messages.length; i++) {
var title = 'Invalid Attribute';
var pointer = '/data/attributes/' + key;
if (key === PRIMARY_ATTRIBUTE_KEY) {
title = 'Invalid Document';
pointer = '/data';
}
out.push({
title: title,
detail: messages[i],
source: {
pointer: pointer
}
});
}
});
}
return out;
}
/**
Convert an array of errors in JSON-API format into an object.
```javascript
import DS from 'ember-data';
const { errorsArrayToHash } = DS;
let errorsArray = [
{
title: 'Invalid Attribute',
detail: 'Must be present',
source: { pointer: '/data/attributes/name' }
},
{
title: 'Invalid Attribute',
detail: 'Must be present',
source: { pointer: '/data/attributes/age' }
},
{
title: 'Invalid Attribute',
detail: 'Must be a number',
source: { pointer: '/data/attributes/age' }
}
];
let errors = errorsArrayToHash(errorsArray);
// {
// "name": ["Must be present"],
// "age": ["Must be present", "must be a number"]
// }
```
@method errorsArrayToHash
@public
@namespace
@for DS
@param {Array} errors array of errors in JSON-API format
@return {Object}
*/
function errorsArrayToHash(errors) {
var out = {};
if (_ember.default.isPresent(errors)) {
errors.forEach(function (error) {
if (error.source && error.source.pointer) {
var key = error.source.pointer.match(SOURCE_POINTER_REGEXP);
if (key) {
key = key[2];
} else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
key = PRIMARY_ATTRIBUTE_KEY;
}
if (key) {
out[key] = out[key] || [];
out[key].push(error.detail || error.title);
}
}
});
}
return out;
}
});
define('ember-data/-private/core', ['exports', 'ember', 'ember-data/version'], function (exports, _ember, _version) {
'use strict';
exports.__esModule = true;
/**
@module ember-data
*/
/**
All Ember Data classes, methods and functions are defined inside of this namespace.
@class DS
@static
*/
/**
@property VERSION
@type String
@static
*/
var DS = _ember.default.Namespace.create({
VERSION: _version.default,
name: "DS"
});
if (_ember.default.libraries) {
_ember.default.libraries.registerCoreLibrary('Ember Data', DS.VERSION);
}
exports.default = DS;
});
define('ember-data/-private/features', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = isEnabled;
function isEnabled() {
var _Ember$FEATURES;
return (_Ember$FEATURES = _ember.default.FEATURES).isEnabled.apply(_Ember$FEATURES, arguments);
}
});
define('ember-data/-private/global', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
/* globals global, window, self */
// originally from https://github.com/emberjs/ember.js/blob/c0bd26639f50efd6a03ee5b87035fd200e313b8e/packages/ember-environment/lib/global.js
// from lodash to catch fake globals
function checkGlobal(value) {
return value && value.Object === Object ? value : undefined;
}
// element ids can ruin global miss checks
function checkElementIdShadowing(value) {
return value && value.nodeType === undefined ? value : undefined;
}
// export real global
exports.default = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || new Function('return this')();
});
define('ember-data/-private', ['exports', 'ember-data/-private/system/model/model', 'ember-data/-private/system/model/errors', 'ember-data/-private/system/store', 'ember-data/-private/core', 'ember-data/-private/system/relationships/belongs-to', 'ember-data/-private/system/relationships/has-many', 'ember-data/-private/adapters/build-url-mixin', 'ember-data/-private/system/snapshot', 'ember-data/-private/adapters/errors', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/utils/parse-response-headers', 'ember-data/-private/global', 'ember-data/-private/features', 'ember-data/-private/system/model/states', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/record-arrays', 'ember-data/-private/system/many-array', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/relationships/state/relationship', 'ember-data/-private/system/debug/debug-adapter', 'ember-data/-private/system/diff-array', 'ember-data/-private/system/relationships/relationship-payloads-manager', 'ember-data/-private/system/relationships/relationship-payloads', 'ember-data/-private/system/snapshot-record-array'], function (exports, _model, _errors, _store, _core, _belongsTo, _hasMany, _buildUrlMixin, _snapshot, _errors2, _normalizeModelName, _utils, _coerceId, _parseResponseHeaders, _global, _features, _states, _internalModel, _containerInstanceCache, _promiseProxies, _recordArrays, _manyArray, _recordArrayManager, _relationship, _debugAdapter, _diffArray, _relationshipPayloadsManager, _relationshipPayloads, _snapshotRecordArray) {
'use strict';
exports.__esModule = true;
Object.defineProperty(exports, 'Model', {
enumerable: true,
get: function () {
return _model.default;
}
});
Object.defineProperty(exports, 'Errors', {
enumerable: true,
get: function () {
return _errors.default;
}
});
Object.defineProperty(exports, 'Store', {
enumerable: true,
get: function () {
return _store.default;
}
});
Object.defineProperty(exports, 'DS', {
enumerable: true,
get: function () {
return _core.default;
}
});
Object.defineProperty(exports, 'belongsTo', {
enumerable: true,
get: function () {
return _belongsTo.default;
}
});
Object.defineProperty(exports, 'hasMany', {
enumerable: true,
get: function () {
return _hasMany.default;
}
});
Object.defineProperty(exports, 'BuildURLMixin', {
enumerable: true,
get: function () {
return _buildUrlMixin.default;
}
});
Object.defineProperty(exports, 'Snapshot', {
enumerable: true,
get: function () {
return _snapshot.default;
}
});
Object.defineProperty(exports, 'AdapterError', {
enumerable: true,
get: function () {
return _errors2.AdapterError;
}
});
Object.defineProperty(exports, 'InvalidError', {
enumerable: true,
get: function () {
return _errors2.InvalidError;
}
});
Object.defineProperty(exports, 'UnauthorizedError', {
enumerable: true,
get: function () {
return _errors2.UnauthorizedError;
}
});
Object.defineProperty(exports, 'ForbiddenError', {
enumerable: true,
get: function () {
return _errors2.ForbiddenError;
}
});
Object.defineProperty(exports, 'NotFoundError', {
enumerable: true,
get: function () {
return _errors2.NotFoundError;
}
});
Object.defineProperty(exports, 'ConflictError', {
enumerable: true,
get: function () {
return _errors2.ConflictError;
}
});
Object.defineProperty(exports, 'ServerError', {
enumerable: true,
get: function () {
return _errors2.ServerError;
}
});
Object.defineProperty(exports, 'TimeoutError', {
enumerable: true,
get: function () {
return _errors2.TimeoutError;
}
});
Object.defineProperty(exports, 'AbortError', {
enumerable: true,
get: function () {
return _errors2.AbortError;
}
});
Object.defineProperty(exports, 'errorsHashToArray', {
enumerable: true,
get: function () {
return _errors2.errorsHashToArray;
}
});
Object.defineProperty(exports, 'errorsArrayToHash', {
enumerable: true,
get: function () {
return _errors2.errorsArrayToHash;
}
});
Object.defineProperty(exports, 'normalizeModelName', {
enumerable: true,
get: function () {
return _normalizeModelName.default;
}
});
Object.defineProperty(exports, 'getOwner', {
enumerable: true,
get: function () {
return _utils.getOwner;
}
});
Object.defineProperty(exports, 'modelHasAttributeOrRelationshipNamedType', {
enumerable: true,
get: function () {
return _utils.modelHasAttributeOrRelationshipNamedType;
}
});
Object.defineProperty(exports, 'coerceId', {
enumerable: true,
get: function () {
return _coerceId.default;
}
});
Object.defineProperty(exports, 'parseResponseHeaders', {
enumerable: true,
get: function () {
return _parseResponseHeaders.default;
}
});
Object.defineProperty(exports, 'global', {
enumerable: true,
get: function () {
return _global.default;
}
});
Object.defineProperty(exports, 'isEnabled', {
enumerable: true,
get: function () {
return _features.default;
}
});
Object.defineProperty(exports, 'RootState', {
enumerable: true,
get: function () {
return _states.default;
}
});
Object.defineProperty(exports, 'InternalModel', {
enumerable: true,
get: function () {
return _internalModel.default;
}
});
Object.defineProperty(exports, 'ContainerInstanceCache', {
enumerable: true,
get: function () {
return _containerInstanceCache.default;
}
});
Object.defineProperty(exports, 'PromiseArray', {
enumerable: true,
get: function () {
return _promiseProxies.PromiseArray;
}
});
Object.defineProperty(exports, 'PromiseObject', {
enumerable: true,
get: function () {
return _promiseProxies.PromiseObject;
}
});
Object.defineProperty(exports, 'PromiseManyArray', {
enumerable: true,
get: function () {
return _promiseProxies.PromiseManyArray;
}
});
Object.defineProperty(exports, 'RecordArray', {
enumerable: true,
get: function () {
return _recordArrays.RecordArray;
}
});
Object.defineProperty(exports, 'FilteredRecordArray', {
enumerable: true,
get: function () {
return _recordArrays.FilteredRecordArray;
}
});
Object.defineProperty(exports, 'AdapterPopulatedRecordArray', {
enumerable: true,
get: function () {
return _recordArrays.AdapterPopulatedRecordArray;
}
});
Object.defineProperty(exports, 'ManyArray', {
enumerable: true,
get: function () {
return _manyArray.default;
}
});
Object.defineProperty(exports, 'RecordArrayManager', {
enumerable: true,
get: function () {
return _recordArrayManager.default;
}
});
Object.defineProperty(exports, 'Relationship', {
enumerable: true,
get: function () {
return _relationship.default;
}
});
Object.defineProperty(exports, 'DebugAdapter', {
enumerable: true,
get: function () {
return _debugAdapter.default;
}
});
Object.defineProperty(exports, 'diffArray', {
enumerable: true,
get: function () {
return _diffArray.default;
}
});
Object.defineProperty(exports, 'RelationshipPayloadsManager', {
enumerable: true,
get: function () {
return _relationshipPayloadsManager.default;
}
});
Object.defineProperty(exports, 'RelationshipPayloads', {
enumerable: true,
get: function () {
return _relationshipPayloads.default;
}
});
Object.defineProperty(exports, 'SnapshotRecordArray', {
enumerable: true,
get: function () {
return _snapshotRecordArray.default;
}
});
});
define("ember-data/-private/system/clone-null", ["exports"], function (exports) {
"use strict";
exports.__esModule = true;
exports.default = cloneNull;
function cloneNull(source) {
var clone = Object.create(null);
for (var key in source) {
clone[key] = source[key];
}
return clone;
}
});
define('ember-data/-private/system/coerce-id', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = coerceId;
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function coerceId(id) {
if (id === null || id === undefined || id === '') {
return null;
}
if (typeof id === 'string') {
return id;
}
return '' + id;
}
});
define('ember-data/-private/system/debug/debug-adapter', ['exports', 'ember', 'ember-data/-private/system/model/model'], function (exports, _ember, _model) {
'use strict';
exports.__esModule = true;
/**
@module ember-data
*/
var capitalize = _ember.default.String.capitalize;
var underscore = _ember.default.String.underscore;
var assert = _ember.default.assert,
get = _ember.default.get;
exports.default = _ember.default.DataAdapter.extend({
getFilters: function () {
return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }];
},
detect: function (typeClass) {
return typeClass !== _model.default && _model.default.detect(typeClass);
},
columnsForType: function (typeClass) {
var columns = [{
name: 'id',
desc: 'Id'
}];
var count = 0;
var self = this;
get(typeClass, 'attributes').forEach(function (meta, name) {
if (count++ > self.attributeLimit) {
return false;
}
var desc = capitalize(underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function (modelClass, modelName) {
if (arguments.length < 2) {
// Legacy Ember.js < 1.13 support
var containerKey = modelClass._debugContainerKey;
if (containerKey) {
var match = containerKey.match(/model:(.*)/);
if (match) {
modelName = match[1];
}
}
}
assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName);
return this.get('store').peekAll(modelName);
},
getRecordColumnValues: function (record) {
var _this = this;
var count = 0;
var columnValues = { id: get(record, 'id') };
record.eachAttribute(function (key) {
if (count++ > _this.attributeLimit) {
return false;
}
columnValues[key] = get(record, key);
});
return columnValues;
},
getRecordKeywords: function (record) {
var keywords = [];
var keys = _ember.default.A(['id']);
record.eachAttribute(function (key) {
return keys.push(key);
});
keys.forEach(function (key) {
return keywords.push(get(record, key));
});
return keywords;
},
getRecordFilterValues: function (record) {
return {
isNew: record.get('isNew'),
isModified: record.get('hasDirtyAttributes') && !record.get('isNew'),
isClean: !record.get('hasDirtyAttributes')
};
},
getRecordColor: function (record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('hasDirtyAttributes')) {
color = 'blue';
}
return color;
},
observeRecord: function (record, recordUpdated) {
var releaseMethods = _ember.default.A();
var keysToObserve = _ember.default.A(['id', 'isNew', 'hasDirtyAttributes']);
record.eachAttribute(function (key) {
return keysToObserve.push(key);
});
var adapter = this;
keysToObserve.forEach(function (key) {
var handler = function () {
recordUpdated(adapter.wrapRecord(record));
};
_ember.default.addObserver(record, key, handler);
releaseMethods.push(function () {
_ember.default.removeObserver(record, key, handler);
});
});
var release = function () {
releaseMethods.forEach(function (fn) {
return fn();
});
};
return release;
}
});
});
define("ember-data/-private/system/diff-array", ["exports"], function (exports) {
"use strict";
exports.__esModule = true;
exports.default = diffArray;
/**
@namespace
@method diffArray
@private
@param {Array} oldArray the old array
@param {Array} newArray the new array
@return {hash} {
firstChangeIndex: <integer>, // null if no change
addedCount: <integer>, // 0 if no change
removedCount: <integer> // 0 if no change
}
*/
function diffArray(oldArray, newArray) {
var oldLength = oldArray.length;
var newLength = newArray.length;
var shortestLength = Math.min(oldLength, newLength);
var firstChangeIndex = null; // null signifies no changes
// find the first change
for (var i = 0; i < shortestLength; i++) {
// compare each item in the array
if (oldArray[i] !== newArray[i]) {
firstChangeIndex = i;
break;
}
}
if (firstChangeIndex === null && newLength !== oldLength) {
// no change found in the overlapping block
// and array lengths differ,
// so change starts at end of overlap
firstChangeIndex = shortestLength;
}
var addedCount = 0;
var removedCount = 0;
if (firstChangeIndex !== null) {
// we found a change, find the end of the change
var unchangedEndBlockLength = shortestLength - firstChangeIndex;
// walk back from the end of both arrays until we find a change
for (var _i = 1; _i <= shortestLength; _i++) {
// compare each item in the array
if (oldArray[oldLength - _i] !== newArray[newLength - _i]) {
unchangedEndBlockLength = _i - 1;
break;
}
}
addedCount = newLength - unchangedEndBlockLength - firstChangeIndex;
removedCount = oldLength - unchangedEndBlockLength - firstChangeIndex;
}
return {
firstChangeIndex: firstChangeIndex,
addedCount: addedCount,
removedCount: removedCount
};
}
});
define('ember-data/-private/system/identity-map', ['exports', 'ember-data/-private/system/internal-model-map'], function (exports, _internalModelMap) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var IdentityMap = function () {
function IdentityMap() {
_classCallCheck(this, IdentityMap);
this._map = Object.create(null);
}
/**
Retrieves the `InternalModelMap` for a given modelName,
creating one if one did not already exist. This is
similar to `getWithDefault` or `get` on a `MapWithDefault`
@method retrieve
@param modelName a previously normalized modelName
@returns {InternalModelMap} the InternalModelMap for the given modelName
*/
IdentityMap.prototype.retrieve = function retrieve(modelName) {
var map = this._map[modelName];
if (!map) {
map = this._map[modelName] = new _internalModelMap.default(modelName);
}
return map;
};
IdentityMap.prototype.clear = function clear() {
var map = this._map;
var keys = Object.keys(map);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
map[key].clear();
}
};
return IdentityMap;
}();
exports.default = IdentityMap;
});
define('ember-data/-private/system/internal-model-map', ['exports', 'ember-data/-private/system/model/internal-model'], function (exports, _internalModel) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var InternalModelMap = function () {
function InternalModelMap(modelName) {
_classCallCheck(this, InternalModelMap);
this.modelName = modelName;
this._idToModel = Object.create(null);
this._models = [];
this._metadata = null;
}
/**
A "map" of records based on their ID for this modelName
*/
InternalModelMap.prototype.get = function get(id) {
var r = this._idToModel[id];
return r;
};
InternalModelMap.prototype.has = function has(id) {
return !!this._idToModel[id];
};
InternalModelMap.prototype.set = function set(id, internalModel) {
(false && Ember.assert('You cannot index an internalModel by an empty id\'', id));
(false && Ember.assert('You cannot set an index for an internalModel to something other than an internalModel', internalModel instanceof _internalModel.default));
(false && Ember.assert('You cannot set an index for an internalModel that is not in the InternalModelMap', this.contains(internalModel)));
(false && Ember.assert('You cannot update the id index of an InternalModel once set. Attempted to update ' + id + '.', !this.has(id) || this.get(id) === internalModel));
this._idToModel[id] = internalModel;
};
InternalModelMap.prototype.add = function add(internalModel, id) {
(false && Ember.assert('You cannot re-add an already present InternalModel to the InternalModelMap.', !this.contains(internalModel)));
if (id) {
this._idToModel[id] = internalModel;
}
this._models.push(internalModel);
};
InternalModelMap.prototype.remove = function remove(internalModel, id) {
if (id) {
delete this._idToModel[id];
}
var loc = this._models.indexOf(internalModel);
if (loc !== -1) {
this._models.splice(loc, 1);
}
};
InternalModelMap.prototype.contains = function contains(internalModel) {
return this._models.indexOf(internalModel) !== -1;
};
InternalModelMap.prototype.clear = function clear() {
if (this._models) {
var models = this._models;
this._models = [];
for (var i = 0; i < models.length; i++) {
var model = models[i];
model.unloadRecord();
}
}
this._metadata = null;
};
InternalModelMap.prototype.destroy = function destroy() {
this._store = null;
this._modelClass = null;
};
_createClass(InternalModelMap, [{
key: 'idToRecord',
get: function () {
(false && !(false) && Ember.deprecate('Use of InternalModelMap.idToRecord is deprecated, use InternalModelMap.get(id) instead.', false, {
id: 'ds.record-map.idToRecord',
until: '2.13'
}));
return this._idToModel;
}
}, {
key: 'length',
get: function () {
return this._models.length;
}
}, {
key: 'models',
get: function () {
return this._models;
}
}, {
key: 'metadata',
get: function () {
return this._metadata || (this._metadata = Object.create(null));
}
}, {
key: 'type',
get: function () {
throw new Error('InternalModelMap.type is no longer available');
}
}]);
return InternalModelMap;
}();
exports.default = InternalModelMap;
});
define('ember-data/-private/system/is-array-like', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = isArrayLike;
/*
We're using this to detect arrays and "array-like" objects.
This is a copy of the `isArray` method found in `ember-runtime/utils` as we're
currently unable to import non-exposed modules.
This method was previously exposed as `Ember.isArray` but since
https://github.com/emberjs/ember.js/pull/11463 `Ember.isArray` is an alias of
`Array.isArray` hence removing the "array-like" part.
*/
function isArrayLike(obj) {
if (!obj || obj.setInterval) {
return false;
}
if (Array.isArray(obj)) {
return true;
}
if (_ember.default.Array.detect(obj)) {
return true;
}
var type = _ember.default.typeOf(obj);
if ('array' === type) {
return true;
}
if (obj.length !== undefined && 'object' === type) {
return true;
}
return false;
}
});
define('ember-data/-private/system/many-array', ['exports', 'ember', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/diff-array'], function (exports, _ember, _promiseProxies, _common, _diffArray) {
'use strict';
exports.__esModule = true;
var get = _ember.default.get;
exports.default = _ember.default.Object.extend(_ember.default.MutableArray, _ember.default.Evented, {
init: function () {
this._super.apply(this, arguments);
/**
The loading state of this array
@property {Boolean} isLoaded
*/
this.isLoaded = false;
this.length = 0;
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise} promise
@private
*/
this.promise = null;
/**
Metadata associated with the request for async hasMany relationships.
Example
Given that the server returns the following JSON payload when fetching a
hasMany relationship:
```js
{
"comments": [{
"id": 1,
"comment": "This is the first comment",
}, {
// ...
}],
"meta": {
"page": 1,
"total": 5
}
}
```
You can then access the metadata via the `meta` property:
```js
post.get('comments').then(function(comments) {
var meta = comments.get('meta');
// meta.page => 1
// meta.total => 5
});
```
@property {Object} meta
@public
*/
this.meta = this.meta || null;
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
this.isPolymorphic = this.isPolymorphic || false;
/**
The relationship which manages this array.
@property {ManyRelationship} relationship
@private
*/
this.relationship = this.relationship || null;
this.currentState = [];
this.flushCanonical(false);
},
objectAt: function (index) {
var internalModel = this.currentState[index];
if (internalModel === undefined) {
return;
}
return internalModel.getRecord();
},
flushCanonical: function () {
var isInitialized = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
// It’s possible the parent side of the relationship may have been unloaded by this point
if (!(0, _common._objectIsAlive)(this)) {
return;
}
var toSet = this.canonicalState;
//a hack for not removing new records
//TODO remove once we have proper diffing
var newInternalModels = this.currentState.filter(
// only add new internalModels which are not yet in the canonical state of this
// relationship (a new internalModel can be in the canonical state if it has
// been 'acknowleged' to be in the relationship via a store.push)
function (internalModel) {
return internalModel.isNew() && toSet.indexOf(internalModel) === -1;
});
toSet = toSet.concat(newInternalModels);
// diff to find changes
var diff = (0, _diffArray.default)(this.currentState, toSet);
if (diff.firstChangeIndex !== null) {
// it's null if no change found
// we found a change
this.arrayContentWillChange(diff.firstChangeIndex, diff.removedCount, diff.addedCount);
this.set('length', toSet.length);
this.currentState = toSet;
this.arrayContentDidChange(diff.firstChangeIndex, diff.removedCount, diff.addedCount);
if (isInitialized && diff.addedCount > 0) {
//notify only on additions
//TODO only notify if unloaded
this.relationship.notifyHasManyChanged();
}
}
},
internalReplace: function (idx, amt, objects) {
if (!objects) {
objects = [];
}
this.arrayContentWillChange(idx, amt, objects.length);
this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects));
this.set('length', this.currentState.length);
this.arrayContentDidChange(idx, amt, objects.length);
},
//TODO(Igor) optimize
_removeInternalModels: function (internalModels) {
for (var i = 0; i < internalModels.length; i++) {
var index = this.currentState.indexOf(internalModels[i]);
this.internalReplace(index, 1);
}
},
//TODO(Igor) optimize
_addInternalModels: function (internalModels, idx) {
if (idx === undefined) {
idx = this.currentState.length;
}
this.internalReplace(idx, 0, internalModels);
},
replace: function (idx, amt, objects) {
var internalModels = void 0;
if (amt > 0) {
internalModels = this.currentState.slice(idx, idx + amt);
this.get('relationship').removeInternalModels(internalModels);
}
if (objects) {
this.get('relationship').addInternalModels(objects.map(function (obj) {
return obj._internalModel;
}), idx);
}
},
/**
Reloads all of the records in the manyArray. If the manyArray
holds a relationship that was originally fetched using a links url
Ember Data will revisit the original links url to repopulate the
relationship.
If the manyArray holds the result of a `store.query()` reload will
re-run the original query.
Example
```javascript
var user = store.peekRecord('user', 1)
user.login().then(function() {
user.get('permissions').then(function(permissions) {
return permissions.reload();
});
});
```
@method reload
@public
*/
reload: function () {
return this.relationship.reload();
},
/**
Saves all of the records in the `ManyArray`.
Example
```javascript
store.findRecord('inbox', 1).then(function(inbox) {
inbox.get('messages').then(function(messages) {
messages.forEach(function(message) {
message.set('isRead', true);
});
messages.save()
});
});
```
@method save
@return {DS.PromiseArray} promise
*/
save: function () {
var manyArray = this;
var promiseLabel = 'DS: ManyArray#save ' + get(this, 'type');
var promise = _ember.default.RSVP.all(this.invoke("save"), promiseLabel).then(function () {
return manyArray;
}, null, 'DS: ManyArray#save return ManyArray');
return _promiseProxies.PromiseArray.create({ promise: promise });
},
/**
Create a child record within the owner
@method createRecord
@private
@param {Object} hash
@return {DS.Model} record
*/
createRecord: function (hash) {
var store = get(this, 'store');
var type = get(this, 'type');
(false && _ember.default.assert('You cannot add \'' + type.modelName + '\' records to this polymorphic relationship.', !get(this, 'isPolymorphic')));
var record = store.createRecord(type.modelName, hash);
this.pushObject(record);
return record;
}
});
});
define('ember-data/-private/system/model/errors', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
var get = _ember.default.get;
var set = _ember.default.set;
var isEmpty = _ember.default.isEmpty;
var makeArray = _ember.default.makeArray;
var MapWithDefault = _ember.default.MapWithDefault;
/**
@module ember-data
*/
/**
Holds validation errors for a given record, organized by attribute names.
Every `DS.Model` has an `errors` property that is an instance of
`DS.Errors`. This can be used to display validation error
messages returned from the server when a `record.save()` rejects.
For Example, if you had a `User` model that looked like this:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string')
});
```
And you attempted to save a record that did not validate on the backend:
```javascript
let user = store.createRecord('user', {
username: 'tomster',
email: 'invalidEmail'
});
user.save();
```
Your backend would be expected to return an error response that described
the problem, so that error messages can be generated on the app.
API responses will be translated into instances of `DS.Errors` differently,
depending on the specific combination of adapter and serializer used. You
may want to check the documentation or the source code of the libraries
that you are using, to know how they expect errors to be communicated.
Errors can be displayed to the user by accessing their property name
to get an array of all the error objects for that property. Each
error object is a JavaScript object with two keys:
- `message` A string containing the error message from the backend
- `attribute` The name of the property associated with this error message
```handlebars
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
```
You can also access the special `messages` property on the error
object to get an array of all the error strings.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@class Errors
@namespace DS
@extends Ember.Object
@uses Ember.Enumerable
@uses Ember.Evented
*/
exports.default = _ember.default.ArrayProxy.extend(_ember.default.Evented, {
/**
Register with target handler
@method registerHandlers
@param {Object} target
@param {Function} becameInvalid
@param {Function} becameValid
@deprecated
*/
registerHandlers: function (target, becameInvalid, becameValid) {
(false && !(false) && _ember.default.deprecate('Record errors will no longer be evented.', false, {
id: 'ds.errors.registerHandlers',
until: '3.0.0'
}));
this._registerHandlers(target, becameInvalid, becameValid);
},
/**
Register with target handler
@method _registerHandlers
@private
*/
_registerHandlers: function (target, becameInvalid, becameValid) {
this.on('becameInvalid', target, becameInvalid);
this.on('becameValid', target, becameValid);
},
/**
@property errorsByAttributeName
@type {Ember.MapWithDefault}
@private
*/
errorsByAttributeName: _ember.default.computed(function () {
return MapWithDefault.create({
defaultValue: function () {
return _ember.default.A();
}
});
}),
/**
Returns errors for a given attribute
```javascript
let user = store.createRecord('user', {
username: 'tomster',
email: 'invalidEmail'
});
user.save().catch(function(){
user.get('errors').errorsFor('email'); // returns:
// [{attribute: "email", message: "Doesn't look like a valid email."}]
});
```
@method errorsFor
@param {String} attribute
@return {Array}
*/
errorsFor: function (attribute) {
return get(this, 'errorsByAttributeName').get(attribute);
},
/**
An array containing all of the error messages for this
record. This is useful for displaying all errors to the user.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property messages
@type {Array}
*/
messages: _ember.default.computed.mapBy('content', 'message'),
/**
@property content
@type {Array}
@private
*/
content: _ember.default.computed(function () {
return _ember.default.A();
}),
/**
@method unknownProperty
@private
*/
unknownProperty: function (attribute) {
var errors = this.errorsFor(attribute);
if (isEmpty(errors)) {
return null;
}
return errors;
},
/**
Total number of errors.
@property length
@type {Number}
@readOnly
*/
/**
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: _ember.default.computed.not('length').readOnly(),
/**
Adds error messages to a given attribute and sends
`becameInvalid` event to the record.
Example:
```javascript
if (!user.get('username') {
user.get('errors').add('username', 'This field is required');
}
```
@method add
@param {String} attribute
@param {(Array|String)} messages
@deprecated
*/
add: function (attribute, messages) {
(false && _ember.default.warn('Interacting with a record errors object will no longer change the record state.', false, {
id: 'ds.errors.add'
}));
var wasEmpty = get(this, 'isEmpty');
this._add(attribute, messages);
if (wasEmpty && !get(this, 'isEmpty')) {
this.trigger('becameInvalid');
}
},
/**
Adds error messages to a given attribute without sending event.
@method _add
@private
*/
_add: function (attribute, messages) {
messages = this._findOrCreateMessages(attribute, messages);
this.addObjects(messages);
get(this, 'errorsByAttributeName').get(attribute).addObjects(messages);
this.notifyPropertyChange(attribute);
},
/**
@method _findOrCreateMessages
@private
*/
_findOrCreateMessages: function (attribute, messages) {
var errors = this.errorsFor(attribute);
var messagesArray = makeArray(messages);
var _messages = new Array(messagesArray.length);
for (var i = 0; i < messagesArray.length; i++) {
var message = messagesArray[i];
var err = errors.findBy('message', message);
if (err) {
_messages[i] = err;
} else {
_messages[i] = {
attribute: attribute,
message: message
};
}
}
return _messages;
},
/**
Removes all error messages from the given attribute and sends
`becameValid` event to the record if there no more errors left.
Example:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
email: DS.attr('string'),
twoFactorAuth: DS.attr('boolean'),
phone: DS.attr('string')
});
```
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
save: function(user) {
if (!user.get('twoFactorAuth')) {
user.get('errors').remove('phone');
}
user.save();
}
}
});
```
@method remove
@param {String} attribute
@deprecated
*/
remove: function (attribute) {
(false && _ember.default.warn('Interacting with a record errors object will no longer change the record state.', false, {
id: 'ds.errors.remove'
}));
if (get(this, 'isEmpty')) {
return;
}
this._remove(attribute);
if (get(this, 'isEmpty')) {
this.trigger('becameValid');
}
},
/**
Removes all error messages from the given attribute without sending event.
@method _remove
@private
*/
_remove: function (attribute) {
if (get(this, 'isEmpty')) {
return;
}
var content = this.rejectBy('attribute', attribute);
set(this, 'content', content);
get(this, 'errorsByAttributeName').delete(attribute);
this.notifyPropertyChange(attribute);
},
/**
Removes all error messages and sends `becameValid` event
to the record.
Example:
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
retrySave: function(user) {
user.get('errors').clear();
user.save();
}
}
});
```
@method clear
@deprecated
*/
clear: function () {
(false && _ember.default.warn('Interacting with a record errors object will no longer change the record state.', false, {
id: 'ds.errors.clear'
}));
if (get(this, 'isEmpty')) {
return;
}
this._clear();
this.trigger('becameValid');
},
/**
Removes all error messages.
to the record.
@method _clear
@private
*/
_clear: function () {
if (get(this, 'isEmpty')) {
return;
}
var errorsByAttributeName = get(this, 'errorsByAttributeName');
var attributes = _ember.default.A();
errorsByAttributeName.forEach(function (_, attribute) {
attributes.push(attribute);
});
errorsByAttributeName.clear();
attributes.forEach(function (attribute) {
this.notifyPropertyChange(attribute);
}, this);
_ember.default.ArrayProxy.prototype.clear.call(this);
},
/**
Checks if there is error messages for the given attribute.
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
save: function(user) {
if (user.get('errors').has('email')) {
return alert('Please update your email before attempting to save.');
}
user.save();
}
}
});
```
@method has
@param {String} attribute
@return {Boolean} true if there some errors on given attribute
*/
has: function (attribute) {
return !isEmpty(this.errorsFor(attribute));
}
});
});
define('ember-data/-private/system/model/internal-model', ['exports', 'ember', 'ember-data/-private/system/model/states', 'ember-data/-private/system/relationships/state/create', 'ember-data/-private/system/snapshot', 'ember-data/-private/features', 'ember-data/-private/system/ordered-set', 'ember-data/-private/utils', 'ember-data/-private/system/references'], function (exports, _ember, _states, _create, _snapshot, _features, _orderedSet, _utils, _references) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var get = _ember.default.get,
set = _ember.default.set,
copy = _ember.default.copy,
EmberError = _ember.default.Error,
inspect = _ember.default.inspect,
isEmpty = _ember.default.isEmpty,
isEqual = _ember.default.isEqual,
setOwner = _ember.default.setOwner,
run = _ember.default.run,
RSVP = _ember.default.RSVP,
Promise = _ember.default.RSVP.Promise;
var assign = _ember.default.assign || _ember.default.merge;
/*
The TransitionChainMap caches the `state.enters`, `state.setups`, and final state reached
when transitioning from one state to another, so that future transitions can replay the
transition without needing to walk the state tree, collect these hook calls and determine
the state to transition into.
A future optimization would be to build a single chained method out of the collected enters
and setups. It may also be faster to do a two level cache (from: { to }) instead of caching based
on a key that adds the two together.
*/
var TransitionChainMap = Object.create(null);
var _extractPivotNameCache = Object.create(null);
var _splitOnDotCache = Object.create(null);
function splitOnDot(name) {
return _splitOnDotCache[name] || (_splitOnDotCache[name] = name.split('.'));
}
function extractPivotName(name) {
return _extractPivotNameCache[name] || (_extractPivotNameCache[name] = splitOnDot(name)[0]);
}
function areAllModelsUnloaded(internalModels) {
for (var i = 0; i < internalModels.length; ++i) {
var record = internalModels[i]._record;
if (record && !(record.get('isDestroyed') || record.get('isDestroying'))) {
return false;
}
}
return true;
}
// this (and all heimdall instrumentation) will be stripped by a babel transform
// https://github.com/heimdalljs/babel5-plugin-strip-heimdall
var InternalModelReferenceId = 1;
var nextBfsId = 1;
/*
`InternalModel` is the Model class that we use internally inside Ember Data to represent models.
Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class.
We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as
a performance optimization.
`InternalModel` should never be exposed to application code. At the boundaries of the system, in places
like `find`, `push`, etc. we convert between Models and InternalModels.
We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model`
if they are needed.
@private
@class InternalModel
*/
var InternalModel = function () {
function InternalModel(modelName, id, store, data) {
_classCallCheck(this, InternalModel);
this.id = id;
// this ensure ordered set can quickly identify this as unique
this[_ember.default.GUID_KEY] = InternalModelReferenceId++ + 'internal-model';
this.store = store;
this.modelName = modelName;
this._loadingPromise = null;
this._record = null;
this._isDestroyed = false;
this.isError = false;
this._isUpdatingRecordArrays = false; // used by the recordArrayManager
// During dematerialization we don't want to rematerialize the record. The
// reason this might happen is that dematerialization removes records from
// record arrays, and Ember arrays will always `objectAt(0)` and
// `objectAt(len - 1)` to test whether or not `firstObject` or `lastObject`
// have changed.
this._isDematerializing = false;
this._scheduledDestroy = null;
this.resetRecord();
if (data) {
this.__data = data;
}
// caches for lazy getters
this._modelClass = null;
this.__deferredTriggers = null;
this.__recordArrays = null;
this._references = null;
this._recordReference = null;
this.__relationships = null;
this.__implicitRelationships = null;
// Used during the mark phase of unloading to avoid checking the same internal
// model twice in the same scan
this._bfsId = 0;
}
InternalModel.prototype.isHiddenFromRecordArrays = function isHiddenFromRecordArrays() {
// During dematerialization we don't want to rematerialize the record.
// recordWasDeleted can cause other records to rematerialize because it
// removes the internal model from the array and Ember arrays will always
// `objectAt(0)` and `objectAt(len -1)` to check whether `firstObject` or
// `lastObject` have changed. When this happens we don't want those
// models to rematerialize their records.
return this._isDematerializing || this.isDestroyed || this.currentState.stateName === 'root.deleted.saved' || this.isEmpty();
};
InternalModel.prototype.isEmpty = function isEmpty() {
return this.currentState.isEmpty;
};
InternalModel.prototype.isLoading = function isLoading() {
return this.currentState.isLoading;
};
InternalModel.prototype.isLoaded = function isLoaded() {
return this.currentState.isLoaded;
};
InternalModel.prototype.hasDirtyAttributes = function hasDirtyAttributes() {
return this.currentState.hasDirtyAttributes;
};
InternalModel.prototype.isSaving = function isSaving() {
return this.currentState.isSaving;
};
InternalModel.prototype.isDeleted = function isDeleted() {
return this.currentState.isDeleted;
};
InternalModel.prototype.isNew = function isNew() {
return this.currentState.isNew;
};
InternalModel.prototype.isValid = function isValid() {
return this.currentState.isValid;
};
InternalModel.prototype.dirtyType = function dirtyType() {
return this.currentState.dirtyType;
};
InternalModel.prototype.getRecord = function getRecord(properties) {
if (!this._record && !this._isDematerializing) {
// lookupFactory should really return an object that creates
// instances with the injections applied
var createOptions = {
store: this.store,
_internalModel: this,
id: this.id,
currentState: this.currentState,
isError: this.isError,
adapterError: this.error
};
if (typeof properties === 'object' && properties !== null) {
assign(createOptions, properties);
}
if (setOwner) {
// ensure that `getOwner(this)` works inside a model instance
setOwner(createOptions, (0, _utils.getOwner)(this.store));
} else {
createOptions.container = this.store.container;
}
this._record = this.store.modelFactoryFor(this.modelName).create(createOptions);
this._triggerDeferredTriggers();
}
return this._record;
};
InternalModel.prototype.resetRecord = function resetRecord() {
this._record = null;
this.dataHasInitialized = false;
this.isReloading = false;
this.error = null;
this.currentState = _states.default.empty;
this.__attributes = null;
this.__inFlightAttributes = null;
this._data = null;
};
InternalModel.prototype.dematerializeRecord = function dematerializeRecord() {
if (this._record) {
this._isDematerializing = true;
this._record.destroy();
this.destroyRelationships();
this.updateRecordArrays();
this.resetRecord();
}
};
InternalModel.prototype.deleteRecord = function deleteRecord() {
this.send('deleteRecord');
};
InternalModel.prototype.save = function save(options) {
var promiseLabel = "DS: Model#save " + this;
var resolver = RSVP.defer(promiseLabel);
this.store.scheduleSave(this, resolver, options);
return resolver.promise;
};
InternalModel.prototype.startedReloading = function startedReloading() {
this.isReloading = true;
if (this.hasRecord) {
set(this._record, 'isReloading', true);
}
};
InternalModel.prototype.finishedReloading = function finishedReloading() {
this.isReloading = false;
if (this.hasRecord) {
set(this._record, 'isReloading', false);
}
};
InternalModel.prototype.reload = function reload() {
this.startedReloading();
var internalModel = this;
var promiseLabel = "DS: Model#reload of " + this;
return new Promise(function (resolve) {
internalModel.send('reloadRecord', resolve);
}, promiseLabel).then(function () {
internalModel.didCleanError();
return internalModel;
}, function (error) {
internalModel.didError(error);
throw error;
}, "DS: Model#reload complete, update flags").finally(function () {
internalModel.finishedReloading();
internalModel.updateRecordArrays();
});
};
InternalModel.prototype._directlyRelatedInternalModels = function _directlyRelatedInternalModels() {
var _this = this;
var array = [];
this.type.eachRelationship(function (key, relationship) {
if (_this._relationships.has(key)) {
var _relationship = _this._relationships.get(key);
var localRelationships = _relationship.members.toArray();
var serverRelationships = _relationship.canonicalMembers.toArray();
array = array.concat(localRelationships, serverRelationships);
}
});
return array;
};
InternalModel.prototype._allRelatedInternalModels = function _allRelatedInternalModels() {
var array = [];
var queue = [];
var bfsId = nextBfsId++;
queue.push(this);
this._bfsId = bfsId;
while (queue.length > 0) {
var node = queue.shift();
array.push(node);
var related = node._directlyRelatedInternalModels();
for (var i = 0; i < related.length; ++i) {
var internalModel = related[i];
(false && _ember.default.assert('Internal Error: seen a future bfs iteration', internalModel._bfsId <= bfsId));
if (internalModel._bfsId < bfsId) {
queue.push(internalModel);
internalModel._bfsId = bfsId;
}
}
}
return array;
};
InternalModel.prototype.unloadRecord = function unloadRecord() {
this.send('unloadRecord');
this.dematerializeRecord();
if (this._scheduledDestroy === null) {
this._scheduledDestroy = run.schedule('destroy', this, '_checkForOrphanedInternalModels');
}
};
InternalModel.prototype.cancelDestroy = function cancelDestroy() {
(false && _ember.default.assert('You cannot cancel the destruction of an InternalModel once it has already been destroyed', !this.isDestroyed));
this._isDematerializing = false;
run.cancel(this._scheduledDestroy);
this._scheduledDestroy = null;
};
InternalModel.prototype._checkForOrphanedInternalModels = function _checkForOrphanedInternalModels() {
this._isDematerializing = false;
this._scheduledDestroy = null;
if (this.isDestroyed) {
return;
}
this._cleanupOrphanedInternalModels();
};
InternalModel.prototype._cleanupOrphanedInternalModels = function _cleanupOrphanedInternalModels() {
var relatedInternalModels = this._allRelatedInternalModels();
if (areAllModelsUnloaded(relatedInternalModels)) {
for (var i = 0; i < relatedInternalModels.length; ++i) {
var internalModel = relatedInternalModels[i];
if (!internalModel.isDestroyed) {
internalModel.destroy();
}
}
}
};
InternalModel.prototype.eachRelationship = function eachRelationship(callback, binding) {
return this.modelClass.eachRelationship(callback, binding);
};
InternalModel.prototype.destroy = function destroy() {
(false && _ember.default.assert("Cannot destroy an internalModel while its record is materialized", !this._record || this._record.get('isDestroyed') || this._record.get('isDestroying')));
this.store._internalModelDestroyed(this);
this._isDestroyed = true;
};
InternalModel.prototype.eachAttribute = function eachAttribute(callback, binding) {
return this.modelClass.eachAttribute(callback, binding);
};
InternalModel.prototype.inverseFor = function inverseFor(key) {
return this.modelClass.inverseFor(key);
};
InternalModel.prototype.setupData = function setupData(data) {
this.store._internalModelDidReceiveRelationshipData(this.modelName, this.id, data.relationships);
var changedKeys = void 0;
if (this.hasRecord) {
changedKeys = this._changedKeys(data.attributes);
}
assign(this._data, data.attributes);
this.pushedData();
if (this.hasRecord) {
this._record._notifyProperties(changedKeys);
}
this.didInitializeData();
};
InternalModel.prototype.becameReady = function becameReady() {
this.store.recordArrayManager.recordWasLoaded(this);
};
InternalModel.prototype.didInitializeData = function didInitializeData() {
if (!this.dataHasInitialized) {
this.becameReady();
this.dataHasInitialized = true;
}
};
InternalModel.prototype.createSnapshot = function createSnapshot(options) {
return new _snapshot.default(this, options);
};
InternalModel.prototype.loadingData = function loadingData(promise) {
this.send('loadingData', promise);
};
InternalModel.prototype.loadedData = function loadedData() {
this.send('loadedData');
this.didInitializeData();
};
InternalModel.prototype.notFound = function notFound() {
this.send('notFound');
};
InternalModel.prototype.pushedData = function pushedData() {
this.send('pushedData');
};
InternalModel.prototype.flushChangedAttributes = function flushChangedAttributes() {
this._inFlightAttributes = this._attributes;
this._attributes = null;
};
InternalModel.prototype.hasChangedAttributes = function hasChangedAttributes() {
return this.__attributes !== null && Object.keys(this.__attributes).length > 0;
};
InternalModel.prototype.updateChangedAttributes = function updateChangedAttributes() {
var changedAttributes = this.changedAttributes();
var changedAttributeNames = Object.keys(changedAttributes);
var attrs = this._attributes;
for (var i = 0, length = changedAttributeNames.length; i < length; i++) {
var attribute = changedAttributeNames[i];
var data = changedAttributes[attribute];
var oldData = data[0];
var newData = data[1];
if (oldData === newData) {
delete attrs[attribute];
}
}
};
InternalModel.prototype.changedAttributes = function changedAttributes() {
var oldData = this._data;
var currentData = this._attributes;
var inFlightData = this._inFlightAttributes;
var newData = assign(copy(inFlightData), currentData);
var diffData = Object.create(null);
var newDataKeys = Object.keys(newData);
for (var i = 0, length = newDataKeys.length; i < length; i++) {
var key = newDataKeys[i];
diffData[key] = [oldData[key], newData[key]];
}
return diffData;
};
InternalModel.prototype.adapterWillCommit = function adapterWillCommit() {
this.send('willCommit');
};
InternalModel.prototype.adapterDidDirty = function adapterDidDirty() {
this.send('becomeDirty');
this.updateRecordArrays();
};
InternalModel.prototype.send = function send(name, context) {
var currentState = this.currentState;
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
};
InternalModel.prototype.notifyHasManyAdded = function notifyHasManyAdded(key, record, idx) {
if (this.hasRecord) {
this._record.notifyHasManyAdded(key, record, idx);
}
};
InternalModel.prototype.notifyHasManyRemoved = function notifyHasManyRemoved(key, record, idx) {
if (this.hasRecord) {
this._record.notifyHasManyRemoved(key, record, idx);
}
};
InternalModel.prototype.notifyBelongsToChanged = function notifyBelongsToChanged(key, record) {
if (this.hasRecord) {
this._record.notifyBelongsToChanged(key, record);
}
};
InternalModel.prototype.notifyPropertyChange = function notifyPropertyChange(key) {
if (this.hasRecord) {
this._record.notifyPropertyChange(key);
}
};
InternalModel.prototype.rollbackAttributes = function rollbackAttributes() {
var dirtyKeys = void 0;
if (this.hasChangedAttributes()) {
dirtyKeys = Object.keys(this._attributes);
this._attributes = null;
}
if (get(this, 'isError')) {
this._inFlightAttributes = null;
this.didCleanError();
}
//Eventually rollback will always work for relationships
//For now we support it only out of deleted state, because we
//have an explicit way of knowing when the server acked the relationship change
if (this.isDeleted()) {
//TODO: Should probably move this to the state machine somehow
this.becameReady();
}
if (this.isNew()) {
this.clearRelationships();
}
if (this.isValid()) {
this._inFlightAttributes = null;
}
this.send('rolledBack');
if (dirtyKeys && dirtyKeys.length > 0) {
this._record._notifyProperties(dirtyKeys);
}
};
InternalModel.prototype.transitionTo = function transitionTo(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct reference to state objects
var pivotName = extractPivotName(name);
var state = this.currentState;
var transitionMapId = state.stateName + '->' + name;
do {
if (state.exit) {
state.exit(this);
}
state = state.parentState;
} while (!state[pivotName]);
var setups = void 0;
var enters = void 0;
var i = void 0;
var l = void 0;
var map = TransitionChainMap[transitionMapId];
if (map) {
setups = map.setups;
enters = map.enters;
state = map.state;
} else {
setups = [];
enters = [];
var path = splitOnDot(name);
for (i = 0, l = path.length; i < l; i++) {
state = state[path[i]];
if (state.enter) {
enters.push(state);
}
if (state.setup) {
setups.push(state);
}
}
TransitionChainMap[transitionMapId] = { setups: setups, enters: enters, state: state };
}
for (i = 0, l = enters.length; i < l; i++) {
enters[i].enter(this);
}
this.currentState = state;
if (this.hasRecord) {
set(this._record, 'currentState', state);
}
for (i = 0, l = setups.length; i < l; i++) {
setups[i].setup(this);
}
this.updateRecordArrays();
};
InternalModel.prototype._unhandledEvent = function _unhandledEvent(state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + inspect(context) + ".";
}
throw new EmberError(errorMessage);
};
InternalModel.prototype.triggerLater = function triggerLater() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (this._deferredTriggers.push(args) !== 1) {
return;
}
this.store._updateInternalModel(this);
};
InternalModel.prototype._triggerDeferredTriggers = function _triggerDeferredTriggers() {
//TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record,
//but for now, we queue up all the events triggered before the record was materialized, and flush
//them once we have the record
if (!this.hasRecord) {
return;
}
var triggers = this._deferredTriggers;
var record = this._record;
var trigger = record.trigger;
for (var i = 0, l = triggers.length; i < l; i++) {
trigger.apply(record, triggers[i]);
}
triggers.length = 0;
};
InternalModel.prototype.clearRelationships = function clearRelationships() {
var _this2 = this;
this.eachRelationship(function (name, relationship) {
if (_this2._relationships.has(name)) {
var rel = _this2._relationships.get(name);
rel.clear();
rel.removeInverseRelationships();
}
});
Object.keys(this._implicitRelationships).forEach(function (key) {
_this2._implicitRelationships[key].clear();
_this2._implicitRelationships[key].removeInverseRelationships();
});
};
InternalModel.prototype.destroyRelationships = function destroyRelationships() {
var _this3 = this;
this.eachRelationship(function (name, relationship) {
if (_this3._relationships.has(name)) {
var rel = _this3._relationships.get(name);
rel.removeInverseRelationships();
}
});
Object.keys(this._implicitRelationships).forEach(function (key) {
_this3._implicitRelationships[key].removeInverseRelationships();
});
};
InternalModel.prototype.preloadData = function preloadData(preload) {
var _this4 = this;
//TODO(Igor) consider the polymorphic case
Object.keys(preload).forEach(function (key) {
var preloadValue = get(preload, key);
var relationshipMeta = _this4.modelClass.metaForProperty(key);
if (relationshipMeta.isRelationship) {
_this4._preloadRelationship(key, preloadValue);
} else {
_this4._data[key] = preloadValue;
}
});
};
InternalModel.prototype._preloadRelationship = function _preloadRelationship(key, preloadValue) {
var relationshipMeta = this.modelClass.metaForProperty(key);
var modelClass = relationshipMeta.type;
if (relationshipMeta.kind === 'hasMany') {
this._preloadHasMany(key, preloadValue, modelClass);
} else {
this._preloadBelongsTo(key, preloadValue, modelClass);
}
};
InternalModel.prototype._preloadHasMany = function _preloadHasMany(key, preloadValue, modelClass) {
(false && _ember.default.assert("You need to pass in an array to set a hasMany property on a record", Array.isArray(preloadValue)));
var recordsToSet = new Array(preloadValue.length);
for (var i = 0; i < preloadValue.length; i++) {
var recordToPush = preloadValue[i];
recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, modelClass);
}
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).updateInternalModelsFromAdapter(recordsToSet);
};
InternalModel.prototype._preloadBelongsTo = function _preloadBelongsTo(key, preloadValue, modelClass) {
var internalModelToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, modelClass);
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).setInternalModel(internalModelToSet);
};
InternalModel.prototype._convertStringOrNumberIntoInternalModel = function _convertStringOrNumberIntoInternalModel(value, modelClass) {
if (typeof value === 'string' || typeof value === 'number') {
return this.store._internalModelForId(modelClass, value);
}
if (value._internalModel) {
return value._internalModel;
}
return value;
};
InternalModel.prototype.updateRecordArrays = function updateRecordArrays() {
this.store.recordArrayManager.recordDidChange(this);
};
InternalModel.prototype.setId = function setId(id) {
(false && _ember.default.assert('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew()));
this.id = id;
if (this._record.get('id') !== id) {
this._record.set('id', id);
}
};
InternalModel.prototype.didError = function didError(error) {
this.error = error;
this.isError = true;
if (this.hasRecord) {
this._record.setProperties({
isError: true,
adapterError: error
});
}
};
InternalModel.prototype.didCleanError = function didCleanError() {
this.error = null;
this.isError = false;
if (this.hasRecord) {
this._record.setProperties({
isError: false,
adapterError: null
});
}
};
InternalModel.prototype.adapterDidCommit = function adapterDidCommit(data) {
if (data) {
this.store._internalModelDidReceiveRelationshipData(this.modelName, this.id, data.relationships);
data = data.attributes;
}
this.didCleanError();
var changedKeys = this._changedKeys(data);
assign(this._data, this._inFlightAttributes);
if (data) {
assign(this._data, data);
}
this._inFlightAttributes = null;
this.send('didCommit');
this.updateRecordArrays();
if (!data) {
return;
}
this._record._notifyProperties(changedKeys);
};
InternalModel.prototype.addErrorMessageToAttribute = function addErrorMessageToAttribute(attribute, message) {
get(this.getRecord(), 'errors')._add(attribute, message);
};
InternalModel.prototype.removeErrorMessageFromAttribute = function removeErrorMessageFromAttribute(attribute) {
get(this.getRecord(), 'errors')._remove(attribute);
};
InternalModel.prototype.clearErrorMessages = function clearErrorMessages() {
get(this.getRecord(), 'errors')._clear();
};
InternalModel.prototype.hasErrors = function hasErrors() {
var errors = get(this.getRecord(), 'errors');
return !isEmpty(errors);
};
InternalModel.prototype.adapterDidInvalidate = function adapterDidInvalidate(errors) {
var attribute = void 0;
for (attribute in errors) {
if (errors.hasOwnProperty(attribute)) {
this.addErrorMessageToAttribute(attribute, errors[attribute]);
}
}
this.send('becameInvalid');
this._saveWasRejected();
};
InternalModel.prototype.adapterDidError = function adapterDidError(error) {
this.send('becameError');
this.didError(error);
this._saveWasRejected();
};
InternalModel.prototype._saveWasRejected = function _saveWasRejected() {
var keys = Object.keys(this._inFlightAttributes);
if (keys.length > 0) {
var attrs = this._attributes;
for (var i = 0; i < keys.length; i++) {
if (attrs[keys[i]] === undefined) {
attrs[keys[i]] = this._inFlightAttributes[keys[i]];
}
}
}
this._inFlightAttributes = null;
};
InternalModel.prototype._changedKeys = function _changedKeys(updates) {
var changedKeys = [];
if (updates) {
var original = void 0,
i = void 0,
value = void 0,
key = void 0;
var keys = Object.keys(updates);
var length = keys.length;
var hasAttrs = this.hasChangedAttributes();
var attrs = void 0;
if (hasAttrs) {
attrs = this._attributes;
}
original = assign(Object.create(null), this._data);
original = assign(original, this._inFlightAttributes);
for (i = 0; i < length; i++) {
key = keys[i];
value = updates[key];
// A value in _attributes means the user has a local change to
// this attributes. We never override this value when merging
// updates from the backend so we should not sent a change
// notification if the server value differs from the original.
if (hasAttrs === true && attrs[key] !== undefined) {
continue;
}
if (!isEqual(original[key], value)) {
changedKeys.push(key);
}
}
}
return changedKeys;
};
InternalModel.prototype.toString = function toString() {
return '<' + this.modelName + ':' + this.id + '>';
};
InternalModel.prototype.referenceFor = function referenceFor(kind, name) {
var reference = this.references[name];
if (!reference) {
var relationship = this._relationships.get(name);
if (false) {
var modelName = this.modelName;
(false && _ember.default.assert('There is no ' + kind + ' relationship named \'' + name + '\' on a model of modelClass \'' + modelName + '\'', relationship));
var actualRelationshipKind = relationship.relationshipMeta.kind;
(false && _ember.default.assert('You tried to get the \'' + name + '\' relationship on a \'' + modelName + '\' via record.' + kind + '(\'' + name + '\'), but the relationship is of kind \'' + actualRelationshipKind + '\'. Use record.' + actualRelationshipKind + '(\'' + name + '\') instead.', actualRelationshipKind === kind));
}
if (kind === "belongsTo") {
reference = new _references.BelongsToReference(this.store, this, relationship);
} else if (kind === "hasMany") {
reference = new _references.HasManyReference(this.store, this, relationship);
}
this.references[name] = reference;
}
return reference;
};
_createClass(InternalModel, [{
key: 'modelClass',
get: function () {
return this._modelClass || (this._modelClass = this.store._modelFor(this.modelName));
}
}, {
key: 'type',
get: function () {
return this.modelClass;
}
}, {
key: 'recordReference',
get: function () {
if (this._recordReference === null) {
this._recordReference = new _references.RecordReference(this.store, this);
}
return this._recordReference;
}
}, {
key: '_recordArrays',
get: function () {
if (this.__recordArrays === null) {
this.__recordArrays = _orderedSet.default.create();
}
return this.__recordArrays;
}
}, {
key: 'references',
get: function () {
if (this._references === null) {
this._references = Object.create(null);
}
return this._references;
}
}, {
key: '_deferredTriggers',
get: function () {
if (this.__deferredTriggers === null) {
this.__deferredTriggers = [];
}
return this.__deferredTriggers;
}
}, {
key: '_attributes',
get: function () {
if (this.__attributes === null) {
this.__attributes = Object.create(null);
}
return this.__attributes;
},
set: function (v) {
this.__attributes = v;
}
}, {
key: '_relationships',
get: function () {
if (this.__relationships === null) {
this.__relationships = new _create.default(this);
}
return this.__relationships;
}
}, {
key: '_inFlightAttributes',
get: function () {
if (this.__inFlightAttributes === null) {
this.__inFlightAttributes = Object.create(null);
}
return this.__inFlightAttributes;
},
set: function (v) {
this.__inFlightAttributes = v;
}
}, {
key: '_data',
get: function () {
if (this.__data === null) {
this.__data = Object.create(null);
}
return this.__data;
},
set: function (v) {
this.__data = v;
}
}, {
key: '_implicitRelationships',
get: function () {
if (this.__implicitRelationships === null) {
this.__implicitRelationships = Object.create(null);
}
return this.__implicitRelationships;
}
}, {
key: 'isDestroyed',
get: function () {
return this._isDestroyed;
}
}, {
key: 'hasRecord',
get: function () {
return !!this._record;
}
}]);
return InternalModel;
}();
exports.default = InternalModel;
if ((0, _features.default)('ds-rollback-attribute')) {
/*
Returns the latest truth for an attribute - the canonical value, or the
in-flight value.
@method lastAcknowledgedValue
@private
*/
InternalModel.prototype.lastAcknowledgedValue = function lastAcknowledgedValue(key) {
if (key in this._inFlightAttributes) {
return this._inFlightAttributes[key];
} else {
return this._data[key];
}
};
}
});
define('ember-data/-private/system/model/model', ['exports', 'ember', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/model/errors', 'ember-data/-private/features', 'ember-data/-private/system/model/states', 'ember-data/-private/system/relationships/ext'], function (exports, _ember, _promiseProxies, _errors, _features, _states, _ext) {
'use strict';
exports.__esModule = true;
var get = _ember.default.get,
computed = _ember.default.computed,
Map = _ember.default.Map;
/**
@module ember-data
*/
function findPossibleInverses(type, inverseType, name, relationshipsSoFar) {
var possibleRelationships = relationshipsSoFar || [];
var relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) {
return possibleRelationships;
}
var relationships = relationshipMap.get(type.modelName).filter(function (relationship) {
var optionsForRelationship = inverseType.metaForProperty(relationship.name).options;
if (!optionsForRelationship.inverse) {
return true;
}
return name === optionsForRelationship.inverse;
});
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationships);
}
//Recurse to support polymorphism
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, name, possibleRelationships);
}
return possibleRelationships;
}
function intersection(array1, array2) {
var result = [];
array1.forEach(function (element) {
if (array2.indexOf(element) >= 0) {
result.push(element);
}
});
return result;
}
var RESERVED_MODEL_PROPS = ['currentState', 'data', 'store'];
var retrieveFromCurrentState = computed('currentState', function (key) {
return get(this._internalModel.currentState, key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
This is the public API of Ember Data models. If you are using Ember Data
in your application, this is the class you should use.
If you are working on Ember Data internals, you most likely want to be dealing
with `InternalModel`
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var Model = _ember.default.Object.extend(_ember.default.Evented, {
_internalModel: null,
store: null,
__defineNonEnumerable: function (property) {
this[property.name] = property.descriptor.value;
},
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
let record = store.createRecord('model');
record.get('isLoaded'); // true
store.findRecord('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
let record = store.createRecord('model');
record.get('hasDirtyAttributes'); // true
store.findRecord('model', 1).then(function(model) {
model.get('hasDirtyAttributes'); // false
model.set('foo', 'some value');
model.get('hasDirtyAttributes'); // true
});
```
@since 1.13.0
@property hasDirtyAttributes
@type {Boolean}
@readOnly
*/
hasDirtyAttributes: computed('currentState.isDirty', function () {
return this.get('currentState.isDirty');
}),
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
let record = store.createRecord('model');
record.get('isSaving'); // false
let promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`hasDirtyAttributes` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the
change has persisted.
Example
```javascript
let record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('hasDirtyAttributes'); // true
record.get('isSaving'); // false
// Persisting the deletion
let promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('hasDirtyAttributes'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
let record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
let record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record from the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
let record = store.createRecord('model');
record.get('id'); // null
store.findRecord('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: _states.default.empty,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
contains keys corresponding to the invalid property names
and values which are arrays of Javascript objects with two keys:
- `message` A string containing the error message from the backend
- `attribute` The name of the property associated with this error message
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
record.get('errors').get('foo');
// [{message: 'foo should be a number.', attribute: 'foo'}]
});
```
The `errors` property us useful for displaying error messages to
the user.
```handlebars
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
```
You can also access the special `messages` property on the error
object to get an array of all the error strings.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property errors
@type {DS.Errors}
*/
errors: computed(function () {
var errors = _errors.default.create();
errors._registerHandlers(this._internalModel, function () {
this.send('becameInvalid');
}, function () {
this.send('becameValid');
});
return errors;
}).readOnly(),
/**
This property holds the `DS.AdapterError` object with which
last adapter operation was rejected.
@property adapterError
@type {DS.AdapterError}
*/
adapterError: null,
serialize: function (options) {
return this._internalModel.createSnapshot().serialize(options);
},
toJSON: function (options) {
// container is for lazy transform lookups
var serializer = this.store.serializerFor('-default');
var snapshot = this._internalModel.createSnapshot();
return serializer.serialize(snapshot, options);
},
/**
Fired when the record is ready to be interacted with,
that is either loaded from the server or created locally.
@event ready
*/
ready: null,
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: null,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: null,
/**
Fired when a new record is commited to the server.
@event didCreate
*/
didCreate: null,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: null,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: null,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: null,
/**
Fired when the record is rolled back.
@event rolledBack
*/
rolledBack: null,
send: function (name, context) {
return this._internalModel.send(name, context);
},
transitionTo: function (name) {
return this._internalModel.transitionTo(name);
},
deleteRecord: function () {
this._internalModel.deleteRecord();
},
destroyRecord: function (options) {
this.deleteRecord();
return this.save(options);
},
unloadRecord: function () {
if (this.isDestroyed) {
return;
}
this._internalModel.unloadRecord();
},
_notifyProperties: function (keys) {
_ember.default.beginPropertyChanges();
var key = void 0;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
this.notifyPropertyChange(key);
}
_ember.default.endPropertyChanges();
},
changedAttributes: function () {
return this._internalModel.changedAttributes();
},
rollbackAttributes: function () {
this._internalModel.rollbackAttributes();
},
_createSnapshot: function () {
return this._internalModel.createSnapshot();
},
toStringExtension: function () {
return get(this, 'id');
},
save: function (options) {
var _this = this;
return _promiseProxies.PromiseObject.create({
promise: this._internalModel.save(options).then(function () {
return _this;
})
});
},
reload: function () {
var _this2 = this;
return _promiseProxies.PromiseObject.create({
promise: this._internalModel.reload().then(function () {
return _this2;
})
});
},
trigger: function (name) {
var fn = this[name];
if (typeof fn === 'function') {
var length = arguments.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
fn.apply(this, args);
}
this._super.apply(this, arguments);
},
attr: function () {
(false && _ember.default.assert("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false));
},
belongsTo: function (name) {
return this._internalModel.referenceFor('belongsTo', name);
},
hasMany: function (name) {
return this._internalModel.referenceFor('hasMany', name);
},
setId: _ember.default.observer('id', function () {
this._internalModel.setId(this.get('id'));
}),
_debugInfo: function () {
var attributes = ['id'];
var relationships = {};
var expensiveProperties = [];
this.eachAttribute(function (name, meta) {
return attributes.push(name);
});
var groups = [{
name: 'Attributes',
properties: attributes,
expand: true
}];
this.eachRelationship(function (name, relationship) {
var properties = relationships[relationship.kind];
if (properties === undefined) {
properties = relationships[relationship.kind] = [];
groups.push({
name: relationship.name,
properties: properties,
expand: true
});
}
properties.push(name);
expensiveProperties.push(name);
});
groups.push({
name: 'Flags',
properties: ['isLoaded', 'hasDirtyAttributes', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
});
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
},
notifyBelongsToChanged: function (key) {
this.notifyPropertyChange(key);
},
eachRelationship: function (callback, binding) {
this.constructor.eachRelationship(callback, binding);
},
relationshipFor: function (name) {
return get(this.constructor, 'relationshipsByName').get(name);
},
inverseFor: function (key) {
return this.constructor.inverseFor(key, this.store);
},
notifyHasManyAdded: function (key) {
//We need to notifyPropertyChange in the adding case because we need to make sure
//we fetch the newly added record in case it is unloaded
//TODO(Igor): Consider whether we could do this only if the record state is unloaded
//Goes away once hasMany is double promisified
this.notifyPropertyChange(key);
},
eachAttribute: function (callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
/**
@property data
@private
@type {Object}
*/
Object.defineProperty(Model.prototype, 'data', {
get: function () {
return this._internalModel._data;
}
});
if (false) {
Model.reopen({
init: function () {
this._super.apply(this, arguments);
if (!this._internalModel) {
throw new _ember.default.Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.');
}
}
});
}
Model.reopenClass({
isModel: true,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
/**
Represents the model's class name as a string. This can be used to look up the model's class name through
`DS.Store`'s modelFor method.
`modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string.
For example:
```javascript
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'
```
The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
keys to underscore (instead of dasherized), you might use the following code:
```javascript
export default const PostSerializer = DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.underscore(modelName);
}
});
```
@property modelName
@type String
@readonly
@static
*/
modelName: null,
typeForRelationship: function (name, store) {
var relationship = get(this, 'relationshipsByName').get(name);
return relationship && store.modelFor(relationship.type);
},
inverseMap: _ember.default.computed(function () {
return Object.create(null);
}),
inverseFor: function (name, store) {
var inverseMap = get(this, 'inverseMap');
if (inverseMap[name] !== undefined) {
return inverseMap[name];
} else {
var relationship = get(this, 'relationshipsByName').get(name);
if (!relationship) {
inverseMap[name] = null;
return null;
}
var options = relationship.options;
if (options && options.inverse === null) {
// populate the cache with a miss entry so we can skip getting and going
// through `relationshipsByName`
inverseMap[name] = null;
return null;
}
return inverseMap[name] = this._findInverseFor(name, store);
}
},
_findInverseFor: function (name, store) {
var inverseType = this.typeForRelationship(name, store);
if (!inverseType) {
return null;
}
var propertyMeta = this.metaForProperty(name);
//If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })`
var options = propertyMeta.options;
if (options.inverse === null) {
return null;
}
var inverseName = void 0,
inverseKind = void 0,
inverse = void 0;
//If inverse is specified manually, return the inverse
if (options.inverse) {
inverseName = options.inverse;
inverse = _ember.default.get(inverseType, 'relationshipsByName').get(inverseName);
(false && _ember.default.assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName + "' model. This is most likely due to a missing attribute on your model definition.", !_ember.default.isNone(inverse)));
inverseKind = inverse.kind;
} else {
//No inverse was specified manually, we need to use a heuristic to guess one
if (propertyMeta.parentType && propertyMeta.type === propertyMeta.parentType.modelName) {
(false && _ember.default.warn('Detected a reflexive relationship by the name of \'' + name + '\' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.', false, {
id: 'ds.model.reflexive-relationship-without-inverse'
}));
}
var possibleRelationships = findPossibleInverses(this, inverseType, name);
if (possibleRelationships.length === 0) {
return null;
}
var filteredRelationships = possibleRelationships.filter(function (possibleRelationship) {
var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options;
return name === optionsForRelationship.inverse;
});
(false && _ember.default.assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2));
if (filteredRelationships.length === 1) {
possibleRelationships = filteredRelationships;
}
(false && _ember.default.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1));
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
import User from 'app/models/user';
import Post from 'app/models/post';
let relationships = Ember.get(Blog, 'relationships');
relationships.get(User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: _ext.relationshipsDescriptor,
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: _ember.default.computed(function () {
var names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ User, Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: _ext.relatedTypesDescriptor,
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
let relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: _ext.relationshipsByNameDescriptor,
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
```
```js
import Ember from 'ember';
import Blog from 'app/models/blog';
let fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: _ember.default.computed(function () {
var map = Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}).readOnly(),
eachRelationship: function (callback, binding) {
get(this, 'relationshipsByName').forEach(function (relationship, name) {
callback.call(binding, name, relationship);
});
},
eachRelatedType: function (callback, binding) {
var relationshipTypes = get(this, 'relatedTypes');
for (var i = 0; i < relationshipTypes.length; i++) {
var type = relationshipTypes[i];
callback.call(binding, type);
}
},
determineRelationshipType: function (knownSide, store) {
var knownKey = knownSide.key;
var knownKind = knownSide.kind;
var inverse = this.inverseFor(knownKey, store);
// let key;
var otherKind = void 0;
if (!inverse) {
return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
}
// key = inverse.name;
otherKind = inverse.kind;
if (otherKind === 'belongsTo') {
return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
} else {
return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
}
},
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
let attributes = Ember.get(Person, 'attributes')
attributes.forEach(function(meta, name) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: _ember.default.computed(function () {
var _this3 = this;
var map = Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isAttribute) {
(false && _ember.default.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + _this3.toString(), name !== 'id'));
meta.name = name;
map.set(name, meta);
}
});
return map;
}).readOnly(),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr('string'),
birthday: DS.attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
let transformedAttributes = Ember.get(Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: _ember.default.computed(function () {
var map = Map.create();
this.eachAttribute(function (key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}).readOnly(),
eachAttribute: function (callback, binding) {
get(this, 'attributes').forEach(function (meta, name) {
callback.call(binding, name, meta);
});
},
eachTransformedAttribute: function (callback, binding) {
get(this, 'transformedAttributes').forEach(function (type, name) {
callback.call(binding, name, type);
});
}
});
// if `Ember.setOwner` is defined, accessing `this.container` is
// deprecated (but functional). In "standard" Ember usage, this
// deprecation is actually created via an `.extend` of the factory
// inside the container itself, but that only happens on models
// with MODEL_FACTORY_INJECTIONS enabled :(
if (_ember.default.setOwner) {
Object.defineProperty(Model.prototype, 'container', {
configurable: true,
enumerable: false,
get: function () {
(false && !(false) && _ember.default.deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '3.0.0' }));
return this.store.container;
}
});
}
if ((0, _features.default)('ds-rollback-attribute')) {
Model.reopen({
rollbackAttribute: function (attributeName) {
if (attributeName in this._internalModel._attributes) {
this.set(attributeName, this._internalModel.lastAcknowledgedValue(attributeName));
}
}
});
}
if (false) {
Model.reopen({
willMergeMixin: function (props) {
var constructor = this.constructor;
(false && _ember.default.assert('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0]));
(false && _ember.default.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + constructor.toString(), Object.keys(props).indexOf('id') === -1));
},
didDefineProperty: function (proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof _ember.default.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
meta.parentType = proto.constructor;
}
}
});
}
exports.default = Model;
});
define('ember-data/-private/system/model/states', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (This state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What that means is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [hasDirtyAttributes](DS.Model.html#property_hasDirtyAttributes)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
function didSetProperty(internalModel, context) {
if (context.value === context.originalValue) {
delete internalModel._attributes[context.name];
internalModel.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
internalModel.send('becomeDirty');
}
internalModel.updateRecordArrays();
}
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: The adapter did not report any server-side validation
// failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// sent to the adapter yet.
/**
@module ember-data
*/
var DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: didSetProperty,
loadingData: function () {},
propertyWasReset: function (internalModel, name) {
if (!internalModel.hasChangedAttributes()) {
internalModel.send('rolledBack');
}
},
pushedData: function (internalModel) {
internalModel.updateChangedAttributes();
if (!internalModel.hasChangedAttributes()) {
internalModel.transitionTo('loaded.saved');
}
},
becomeDirty: function () {},
willCommit: function (internalModel) {
internalModel.transitionTo('inFlight');
},
reloadRecord: function (internalModel, resolve) {
resolve(internalModel.store._reloadRecord(internalModel));
},
rolledBack: function (internalModel) {
internalModel.transitionTo('loaded.saved');
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
},
rollback: function (internalModel) {
internalModel.rollbackAttributes();
internalModel.triggerLater('ready');
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: didSetProperty,
becomeDirty: function () {},
pushedData: function () {},
unloadRecord: assertAgainstUnloadRecord,
willCommit: function () {},
didCommit: function (internalModel) {
internalModel.transitionTo('saved');
internalModel.send('invokeLifecycleCallbacks', this.dirtyType);
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
internalModel.send('invokeLifecycleCallbacks');
},
becameError: function (internalModel) {
internalModel.transitionTo('uncommitted');
internalModel.triggerLater('becameError', internalModel);
}
},
// A record is in the `invalid` if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
deleteRecord: function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
},
didSetProperty: function (internalModel, context) {
internalModel.removeErrorMessageFromAttribute(context.name);
didSetProperty(internalModel, context);
if (!internalModel.hasErrors()) {
this.becameValid(internalModel);
}
},
becameInvalid: function () {},
becomeDirty: function () {},
pushedData: function () {},
willCommit: function (internalModel) {
internalModel.clearErrorMessages();
internalModel.transitionTo('inFlight');
},
rolledBack: function (internalModel) {
internalModel.clearErrorMessages();
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('ready');
},
becameValid: function (internalModel) {
internalModel.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function (internalModel) {
internalModel.triggerLater('becameInvalid', internalModel);
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function deepClone(object) {
var clone = {};
var value = void 0;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function dirtyState(options) {
var newState = deepClone(DirtyState);
return mixin(newState, options);
}
var createdState = dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
createdState.invalid.rolledBack = function (internalModel) {
internalModel.transitionTo('deleted.saved');
};
createdState.uncommitted.rolledBack = function (internalModel) {
internalModel.transitionTo('deleted.saved');
};
var updatedState = dirtyState({
dirtyType: 'updated'
});
function createdStateDeleteRecord(internalModel) {
internalModel.transitionTo('deleted.saved');
internalModel.send('invokeLifecycleCallbacks');
}
createdState.uncommitted.deleteRecord = createdStateDeleteRecord;
createdState.invalid.deleteRecord = createdStateDeleteRecord;
createdState.uncommitted.rollback = function (internalModel) {
DirtyState.uncommitted.rollback.apply(this, arguments);
internalModel.transitionTo('deleted.saved');
};
createdState.uncommitted.pushedData = function (internalModel) {
internalModel.transitionTo('loaded.updated.uncommitted');
internalModel.triggerLater('didLoad');
};
createdState.uncommitted.propertyWasReset = function () {};
function assertAgainstUnloadRecord(internalModel) {
(false && Ember.assert("You can only unload a record which is not inFlight. `" + internalModel + "`", false));
}
updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord;
updatedState.uncommitted.deleteRecord = function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
};
var RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
rolledBack: function () {},
unloadRecord: function (internalModel) {},
propertyWasReset: function () {},
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
loadingData: function (internalModel, promise) {
internalModel._loadingPromise = promise;
internalModel.transitionTo('loading');
},
loadedData: function (internalModel) {
internalModel.transitionTo('loaded.created.uncommitted');
internalModel.triggerLater('ready');
},
pushedData: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('didLoad');
internalModel.triggerLater('ready');
}
},
// A record enters this state when the store asks
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function (internalModel) {
internalModel._loadingPromise = null;
},
pushedData: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('didLoad');
internalModel.triggerLater('ready');
//TODO this seems out of place here
internalModel.didCleanError();
},
becameError: function (internalModel) {
internalModel.triggerLater('becameError', internalModel);
},
notFound: function (internalModel) {
internalModel.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
loadingData: function () {},
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function (internalModel) {
if (internalModel.hasChangedAttributes()) {
internalModel.adapterDidDirty();
}
},
// EVENTS
didSetProperty: didSetProperty,
pushedData: function () {},
becomeDirty: function (internalModel) {
internalModel.transitionTo('updated.uncommitted');
},
willCommit: function (internalModel) {
internalModel.transitionTo('updated.inFlight');
},
reloadRecord: function (internalModel, resolve) {
resolve(internalModel.store._reloadRecord(internalModel));
},
deleteRecord: function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
},
unloadRecord: function (internalModel) {},
didCommit: function () {},
notFound: function () {}
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
setup: function (internalModel) {
internalModel.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
willCommit: function (internalModel) {
internalModel.transitionTo('inFlight');
},
rollback: function (internalModel) {
internalModel.rollbackAttributes();
internalModel.triggerLater('ready');
},
pushedData: function () {},
becomeDirty: function () {},
deleteRecord: function () {},
rolledBack: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('ready');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
unloadRecord: assertAgainstUnloadRecord,
willCommit: function () {},
didCommit: function (internalModel) {
internalModel.transitionTo('saved');
internalModel.send('invokeLifecycleCallbacks');
},
becameError: function (internalModel) {
internalModel.transitionTo('uncommitted');
internalModel.triggerLater('becameError', internalModel);
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
internalModel.triggerLater('becameInvalid', internalModel);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function (internalModel) {
internalModel.clearRelationships();
},
invokeLifecycleCallbacks: function (internalModel) {
internalModel.triggerLater('didDelete', internalModel);
internalModel.triggerLater('didCommit', internalModel);
},
willCommit: function () {},
didCommit: function () {}
},
invalid: {
isValid: false,
didSetProperty: function (internalModel, context) {
internalModel.removeErrorMessageFromAttribute(context.name);
didSetProperty(internalModel, context);
if (!internalModel.hasErrors()) {
this.becameValid(internalModel);
}
},
becameInvalid: function () {},
becomeDirty: function () {},
deleteRecord: function () {},
willCommit: function () {},
rolledBack: function (internalModel) {
internalModel.clearErrorMessages();
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('ready');
},
becameValid: function (internalModel) {
internalModel.transitionTo('uncommitted');
}
}
},
invokeLifecycleCallbacks: function (internalModel, dirtyType) {
if (dirtyType === 'created') {
internalModel.triggerLater('didCreate', internalModel);
} else {
internalModel.triggerLater('didUpdate', internalModel);
}
internalModel.triggerLater('didCommit', internalModel);
}
};
function wireState(object, parent, name) {
// TODO: Use Object.create and copy instead
object = mixin(parent ? Object.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') {
continue;
}
if (typeof object[prop] === 'object') {
object[prop] = wireState(object[prop], object, name + '.' + prop);
}
}
return object;
}
exports.default = wireState(RootState, null, 'root');
});
define('ember-data/-private/system/normalize-link', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = _normalizeLink;
/*
This method normalizes a link to an "links object". If the passed link is
already an object it's returned without any modifications.
See http://jsonapi.org/format/#document-links for more information.
@method _normalizeLink
@private
@param {String} link
@return {Object|null}
@for DS
*/
function _normalizeLink(link) {
switch (typeof link) {
case 'object':
return link;
case 'string':
return { href: link };
}
return null;
}
});
define('ember-data/-private/system/normalize-model-name', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = normalizeModelName;
// All modelNames are dasherized internally. Changing this function may
// require changes to other normalization hooks (such as typeForRoot).
/**
This method normalizes a modelName into the format Ember Data uses
internally.
@method normalizeModelName
@public
@param {String} modelName
@return {String} normalizedModelName
@for DS
*/
function normalizeModelName(modelName) {
return _ember.default.String.dasherize(modelName);
}
});
define('ember-data/-private/system/ordered-set', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = OrderedSet;
var EmberOrderedSet = _ember.default.OrderedSet;
var guidFor = _ember.default.guidFor;
function OrderedSet() {
this._super$constructor();
}
OrderedSet.create = function () {
var Constructor = this;
return new Constructor();
};
OrderedSet.prototype = Object.create(EmberOrderedSet.prototype);
OrderedSet.prototype.constructor = OrderedSet;
OrderedSet.prototype._super$constructor = EmberOrderedSet;
OrderedSet.prototype.addWithIndex = function (obj, idx) {
var guid = guidFor(obj);
var presenceSet = this.presenceSet;
var list = this.list;
if (presenceSet[guid] === true) {
return;
}
presenceSet[guid] = true;
if (idx === undefined || idx === null) {
list.push(obj);
} else {
list.splice(idx, 0, obj);
}
this.size += 1;
return this;
};
});
define('ember-data/-private/system/promise-proxies', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.PromiseManyArray = exports.PromiseObject = exports.PromiseArray = undefined;
exports.promiseObject = promiseObject;
exports.promiseArray = promiseArray;
exports.proxyToContent = proxyToContent;
exports.promiseManyArray = promiseManyArray;
var get = _ember.default.get,
Promise = _ember.default.RSVP.Promise;
/**
A `PromiseArray` is an object that acts like both an `Ember.Array`
and a promise. When the promise is resolved the resulting value
will be set to the `PromiseArray`'s `content` property. This makes
it easy to create data bindings with the `PromiseArray` that will be
updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
let promiseArray = DS.PromiseArray.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseArray.get('length'); // 0
promiseArray.then(function() {
promiseArray.get('length'); // 100
});
```
@class PromiseArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.PromiseProxyMixin
*/
var PromiseArray = exports.PromiseArray = _ember.default.ArrayProxy.extend(_ember.default.PromiseProxyMixin);
/**
A `PromiseObject` is an object that acts like both an `Ember.Object`
and a promise. When the promise is resolved, then the resulting value
will be set to the `PromiseObject`'s `content` property. This makes
it easy to create data bindings with the `PromiseObject` that will
be updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
let promiseObject = DS.PromiseObject.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseObject.get('name'); // null
promiseObject.then(function() {
promiseObject.get('name'); // 'Tomster'
});
```
@class PromiseObject
@namespace DS
@extends Ember.ObjectProxy
@uses Ember.PromiseProxyMixin
*/
var PromiseObject = exports.PromiseObject = _ember.default.ObjectProxy.extend(_ember.default.PromiseProxyMixin);
function promiseObject(promise, label) {
return PromiseObject.create({
promise: Promise.resolve(promise, label)
});
}
function promiseArray(promise, label) {
return PromiseArray.create({
promise: Promise.resolve(promise, label)
});
}
/**
A PromiseManyArray is a PromiseArray that also proxies certain method calls
to the underlying manyArray.
Right now we proxy:
* `reload()`
* `createRecord()`
* `on()`
* `one()`
* `trigger()`
* `off()`
* `has()`
@class PromiseManyArray
@namespace DS
@extends Ember.ArrayProxy
*/
function proxyToContent(method) {
return function () {
var _get;
return (_get = get(this, 'content'))[method].apply(_get, arguments);
};
}
var PromiseManyArray = exports.PromiseManyArray = PromiseArray.extend({
reload: function () {
(false && _ember.default.assert('You are trying to reload an async manyArray before it has been created', get(this, 'content')));
this.set('promise', this.get('content').reload());
return this;
},
createRecord: proxyToContent('createRecord'),
on: proxyToContent('on'),
one: proxyToContent('one'),
trigger: proxyToContent('trigger'),
off: proxyToContent('off'),
has: proxyToContent('has')
});
function promiseManyArray(promise, label) {
return PromiseManyArray.create({
promise: Promise.resolve(promise, label)
});
}
});
define("ember-data/-private/system/record-array-manager", ["exports", "ember", "ember-data/-private/system/record-arrays", "ember-data/-private/system/clone-null"], function (exports, _ember, _recordArrays, _cloneNull) {
"use strict";
exports.__esModule = true;
exports.associateWithRecordArray = associateWithRecordArray;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var get = _ember.default.get,
set = _ember.default.set,
emberRun = _ember.default.run;
var RecordArrayManager = function () {
function RecordArrayManager(options) {
_classCallCheck(this, RecordArrayManager);
this.store = options.store;
this.isDestroying = false;
this.isDestroyed = false;
this._filteredRecordArrays = Object.create(null);
this._liveRecordArrays = Object.create(null);
this._pending = Object.create(null);
this._adapterPopulatedRecordArrays = [];
}
RecordArrayManager.prototype.recordDidChange = function recordDidChange(internalModel) {
// TODO: change name
// TODO: track that it was also a change
this.internalModelDidChange(internalModel);
};
RecordArrayManager.prototype.recordWasLoaded = function recordWasLoaded(internalModel) {
// TODO: change name
// TODO: track that it was also that it was first loaded
this.internalModelDidChange(internalModel);
};
RecordArrayManager.prototype.internalModelDidChange = function internalModelDidChange(internalModel) {
var modelName = internalModel.modelName;
if (internalModel._pendingRecordArrayManagerFlush) {
return;
}
internalModel._pendingRecordArrayManagerFlush = true;
var pending = this._pending;
var models = pending[modelName] = pending[modelName] || [];
if (models.push(internalModel) !== 1) {
return;
}
emberRun.schedule('actions', this, this._flush);
};
RecordArrayManager.prototype._flush = function _flush() {
var pending = this._pending;
this._pending = Object.create(null);
var modelsToRemove = [];
for (var modelName in pending) {
var internalModels = pending[modelName];
for (var j = 0; j < internalModels.length; j++) {
var internalModel = internalModels[j];
// mark internalModels, so they can once again be processed by the
// recordArrayManager
internalModel._pendingRecordArrayManagerFlush = false;
// build up a set of models to ensure we have purged correctly;
if (internalModel.isHiddenFromRecordArrays()) {
modelsToRemove.push(internalModel);
}
}
// process filteredRecordArrays
if (this._filteredRecordArrays[modelName]) {
var recordArrays = this.filteredRecordArraysFor(modelName);
for (var i = 0; i < recordArrays.length; i++) {
this.updateFilterRecordArray(recordArrays[i], modelName, internalModels);
}
}
var array = this._liveRecordArrays[modelName];
if (array) {
// TODO: skip if it only changed
// process liveRecordArrays
this.updateLiveRecordArray(array, internalModels);
}
// process adapterPopulatedRecordArrays
if (modelsToRemove.length > 0) {
removeFromAdapterPopulatedRecordArrays(modelsToRemove);
}
}
};
RecordArrayManager.prototype.updateLiveRecordArray = function updateLiveRecordArray(array, internalModels) {
return _updateLiveRecordArray(array, internalModels);
};
RecordArrayManager.prototype.updateFilterRecordArray = function updateFilterRecordArray(array, modelName, internalModels) {
var filter = get(array, 'filterFunction');
var shouldBeInAdded = [];
var shouldBeRemoved = [];
for (var i = 0; i < internalModels.length; i++) {
var internalModel = internalModels[i];
if (internalModel.isHiddenFromRecordArrays() === false && filter(internalModel.getRecord())) {
if (internalModel._recordArrays.has(array)) {
continue;
}
shouldBeInAdded.push(internalModel);
internalModel._recordArrays.add(array);
} else {
if (internalModel._recordArrays.delete(array)) {
shouldBeRemoved.push(internalModel);
}
}
}
if (shouldBeInAdded.length > 0) {
array._pushInternalModels(shouldBeInAdded);
}
if (shouldBeRemoved.length > 0) {
array._removeInternalModels(shouldBeRemoved);
}
};
RecordArrayManager.prototype._syncLiveRecordArray = function _syncLiveRecordArray(array, modelName) {
(false && _ember.default.assert("recordArrayManger.syncLiveRecordArray expects modelName not modelClass as the second param", typeof modelName === 'string'));
var hasNoPotentialDeletions = Object.keys(this._pending).length === 0;
var map = this.store._internalModelsFor(modelName);
var hasNoInsertionsOrRemovals = get(map, 'length') === get(array, 'length');
/*
Ideally the recordArrayManager has knowledge of the changes to be applied to
liveRecordArrays, and is capable of strategically flushing those changes and applying
small diffs if desired. However, until we've refactored recordArrayManager, this dirty
check prevents us from unnecessarily wiping out live record arrays returned by peekAll.
*/
if (hasNoPotentialDeletions && hasNoInsertionsOrRemovals) {
return;
}
var internalModels = this._visibleInternalModelsByType(modelName);
var modelsToAdd = [];
for (var i = 0; i < internalModels.length; i++) {
var internalModel = internalModels[i];
var recordArrays = internalModel._recordArrays;
if (recordArrays.has(array) === false) {
recordArrays.add(array);
modelsToAdd.push(internalModel);
}
}
array._pushInternalModels(modelsToAdd);
};
RecordArrayManager.prototype.updateFilter = function updateFilter(array, modelName, filter) {
(false && _ember.default.assert("recordArrayManger.updateFilter expects modelName not modelClass as the second param, received " + modelName, typeof modelName === 'string'));
var modelMap = this.store._internalModelsFor(modelName);
var internalModels = modelMap.models;
this.updateFilterRecordArray(array, filter, internalModels);
};
RecordArrayManager.prototype._didUpdateAll = function _didUpdateAll(modelName) {
var recordArray = this._liveRecordArrays[modelName];
if (recordArray) {
set(recordArray, 'isUpdating', false);
}
};
RecordArrayManager.prototype.liveRecordArrayFor = function liveRecordArrayFor(modelName) {
(false && _ember.default.assert("recordArrayManger.liveRecordArrayFor expects modelName not modelClass as the param", typeof modelName === 'string'));
var array = this._liveRecordArrays[modelName];
if (array) {
// if the array already exists, synchronize
this._syncLiveRecordArray(array, modelName);
} else {
// if the array is being newly created merely create it with its initial
// content already set. This prevents unneeded change events.
var internalModels = this._visibleInternalModelsByType(modelName);
array = this.createRecordArray(modelName, internalModels);
this._liveRecordArrays[modelName] = array;
}
return array;
};
RecordArrayManager.prototype._visibleInternalModelsByType = function _visibleInternalModelsByType(modelName) {
var all = this.store._internalModelsFor(modelName)._models;
var visible = [];
for (var i = 0; i < all.length; i++) {
var model = all[i];
if (model.isHiddenFromRecordArrays() === false) {
visible.push(model);
}
}
return visible;
};
RecordArrayManager.prototype.filteredRecordArraysFor = function filteredRecordArraysFor(modelName) {
(false && _ember.default.assert("recordArrayManger.filteredRecordArraysFor expects modelName not modelClass as the param", typeof modelName === 'string'));
return this._filteredRecordArrays[modelName] || (this._filteredRecordArrays[modelName] = []);
};
RecordArrayManager.prototype.createRecordArray = function createRecordArray(modelName, content) {
(false && _ember.default.assert("recordArrayManger.createRecordArray expects modelName not modelClass as the param", typeof modelName === 'string'));
var array = _recordArrays.RecordArray.create({
modelName: modelName,
content: _ember.default.A(content || []),
store: this.store,
isLoaded: true,
manager: this
});
if (Array.isArray(content)) {
associateWithRecordArray(content, array);
}
return array;
};
RecordArrayManager.prototype.createFilteredRecordArray = function createFilteredRecordArray(modelName, filter, query) {
(false && _ember.default.assert("recordArrayManger.createFilteredRecordArray expects modelName not modelClass as the first param, received " + modelName, typeof modelName === 'string'));
var array = _recordArrays.FilteredRecordArray.create({
query: query,
modelName: modelName,
content: _ember.default.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, modelName, filter);
return array;
};
RecordArrayManager.prototype.createAdapterPopulatedRecordArray = function createAdapterPopulatedRecordArray(modelName, query, internalModels, payload) {
(false && _ember.default.assert("recordArrayManger.createAdapterPopulatedRecordArray expects modelName not modelClass as the first param, received " + modelName, typeof modelName === 'string'));
var array = void 0;
if (Array.isArray(internalModels)) {
array = _recordArrays.AdapterPopulatedRecordArray.create({
modelName: modelName,
query: query,
content: _ember.default.A(internalModels),
store: this.store,
manager: this,
isLoaded: true,
isUpdating: false,
meta: (0, _cloneNull.default)(payload.meta),
links: (0, _cloneNull.default)(payload.links)
});
associateWithRecordArray(internalModels, array);
} else {
array = _recordArrays.AdapterPopulatedRecordArray.create({
modelName: modelName,
query: query,
content: _ember.default.A(),
store: this.store,
manager: this
});
}
this._adapterPopulatedRecordArrays.push(array);
return array;
};
RecordArrayManager.prototype.registerFilteredRecordArray = function registerFilteredRecordArray(array, modelName, filter) {
(false && _ember.default.assert("recordArrayManger.registerFilteredRecordArray expects modelName not modelClass as the second param, received " + modelName, typeof modelName === 'string'));
this.filteredRecordArraysFor(modelName).push(array);
this.updateFilter(array, modelName, filter);
};
RecordArrayManager.prototype.unregisterRecordArray = function unregisterRecordArray(array) {
var modelName = array.modelName;
// unregister filtered record array
var recordArrays = this.filteredRecordArraysFor(modelName);
var removedFromFiltered = remove(recordArrays, array);
// remove from adapter populated record array
var removedFromAdapterPopulated = remove(this._adapterPopulatedRecordArrays, array);
if (!removedFromFiltered && !removedFromAdapterPopulated) {
var liveRecordArrayForType = this._liveRecordArrays[modelName];
// unregister live record array
if (liveRecordArrayForType) {
if (array === liveRecordArrayForType) {
delete this._liveRecordArrays[modelName];
}
}
}
};
RecordArrayManager.prototype.willDestroy = function willDestroy() {
var _this = this;
Object.keys(this._filteredRecordArrays).forEach(function (modelName) {
return flatten(_this._filteredRecordArrays[modelName]).forEach(destroy);
});
Object.keys(this._liveRecordArrays).forEach(function (modelName) {
return _this._liveRecordArrays[modelName].destroy();
});
this._adapterPopulatedRecordArrays.forEach(destroy);
this.isDestroyed = true;
};
RecordArrayManager.prototype.destroy = function destroy() {
this.isDestroying = true;
_ember.default.run.schedule('actions', this, this.willDestroy);
};
return RecordArrayManager;
}();
exports.default = RecordArrayManager;
function destroy(entry) {
entry.destroy();
}
function flatten(list) {
var length = list.length;
var result = [];
for (var i = 0; i < length; i++) {
result = result.concat(list[i]);
}
return result;
}
function remove(array, item) {
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
return true;
}
return false;
}
function _updateLiveRecordArray(array, internalModels) {
var modelsToAdd = [];
var modelsToRemove = [];
for (var i = 0; i < internalModels.length; i++) {
var internalModel = internalModels[i];
var isDeleted = internalModel.isHiddenFromRecordArrays();
var recordArrays = internalModel._recordArrays;
if (!isDeleted && !internalModel.isEmpty()) {
if (!recordArrays.has(array)) {
modelsToAdd.push(internalModel);
recordArrays.add(array);
}
}
if (isDeleted) {
modelsToRemove.push(internalModel);
recordArrays.delete(array);
}
}
if (modelsToAdd.length > 0) {
array._pushInternalModels(modelsToAdd);
}
if (modelsToRemove.length > 0) {
array._removeInternalModels(modelsToRemove);
}
}
function removeFromAdapterPopulatedRecordArrays(internalModels) {
for (var i = 0; i < internalModels.length; i++) {
var internalModel = internalModels[i];
var list = internalModel._recordArrays.list;
for (var j = 0; j < list.length; j++) {
// TODO: group by arrays, so we can batch remove
list[j]._removeInternalModels([internalModel]);
}
internalModel._recordArrays.clear();
}
}
function associateWithRecordArray(internalModels, array) {
for (var i = 0, l = internalModels.length; i < l; i++) {
var internalModel = internalModels[i];
internalModel._recordArrays.add(array);
}
}
});
define("ember-data/-private/system/record-arrays", ["exports", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/record-arrays/filtered-record-array", "ember-data/-private/system/record-arrays/adapter-populated-record-array"], function (exports, _recordArray, _filteredRecordArray, _adapterPopulatedRecordArray) {
"use strict";
exports.__esModule = true;
exports.AdapterPopulatedRecordArray = exports.FilteredRecordArray = exports.RecordArray = undefined;
exports.RecordArray = _recordArray.default;
exports.FilteredRecordArray = _filteredRecordArray.default;
exports.AdapterPopulatedRecordArray = _adapterPopulatedRecordArray.default;
});
define("ember-data/-private/system/record-arrays/adapter-populated-record-array", ["exports", "ember", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/clone-null", "ember-data/-private/system/record-array-manager"], function (exports, _ember, _recordArray, _cloneNull, _recordArrayManager) {
"use strict";
exports.__esModule = true;
var get = _ember.default.get;
exports.default = _recordArray.default.extend({
init: function () {
// yes we are touching `this` before super, but ArrayProxy has a bug that requires this.
this.set('content', this.get('content') || _ember.default.A());
this._super.apply(this, arguments);
this.query = this.query || null;
this.links = null;
},
replace: function () {
throw new Error("The result of a server query (on " + this.modelName + ") is immutable.");
},
_update: function () {
var store = get(this, 'store');
var query = get(this, 'query');
return store._query(this.modelName, query, this);
},
/**
@method _setInternalModels
@param {Array} internalModels
@param {Object} payload normalized payload
@private
*/
_setInternalModels: function (internalModels, payload) {
// TODO: initial load should not cause change events at all, only
// subsequent. This requires changing the public api of adapter.query, but
// hopefully we can do that soon.
this.get('content').setObjects(internalModels);
this.setProperties({
isLoaded: true,
isUpdating: false,
meta: (0, _cloneNull.default)(payload.meta),
links: (0, _cloneNull.default)(payload.links)
});
(0, _recordArrayManager.associateWithRecordArray)(internalModels, this);
// TODO: should triggering didLoad event be the last action of the runLoop?
_ember.default.run.once(this, 'trigger', 'didLoad');
}
});
});
define('ember-data/-private/system/record-arrays/filtered-record-array', ['exports', 'ember', 'ember-data/-private/system/record-arrays/record-array'], function (exports, _ember, _recordArray) {
'use strict';
exports.__esModule = true;
var get = _ember.default.get;
exports.default = _recordArray.default.extend({
init: function () {
this._super.apply(this, arguments);
this.set('filterFunction', this.get('filterFunction') || null);
this.isLoaded = true;
},
/**
The filterFunction is a function used to test records from the store to
determine if they should be part of the record array.
Example
```javascript
var allPeople = store.peekAll('person');
allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
var people = store.filter('person', function(person) {
if (person.get('name').match(/Katz$/)) { return true; }
});
people.mapBy('name'); // ["Yehuda Katz"]
var notKatzFilter = function(person) {
return !person.get('name').match(/Katz$/);
};
people.set('filterFunction', notKatzFilter);
people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
```
@method filterFunction
@param {DS.Model} record
@return {Boolean} `true` if the record should be in the array
*/
replace: function () {
throw new Error('The result of a client-side filter (on ' + this.modelName + ') is immutable.');
},
/**
@method updateFilter
@private
*/
_updateFilter: function () {
if (get(this, 'isDestroying') || get(this, 'isDestroyed')) {
return;
}
get(this, 'manager').updateFilter(this, this.modelName, get(this, 'filterFunction'));
},
updateFilter: _ember.default.observer('filterFunction', function () {
_ember.default.run.once(this, this._updateFilter);
})
});
});
define("ember-data/-private/system/record-arrays/record-array", ["exports", "ember", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/snapshot-record-array"], function (exports, _ember, _promiseProxies, _snapshotRecordArray) {
"use strict";
exports.__esModule = true;
var computed = _ember.default.computed,
get = _ember.default.get,
set = _ember.default.set,
Promise = _ember.default.RSVP.Promise;
exports.default = _ember.default.ArrayProxy.extend(_ember.default.Evented, {
init: function () {
this._super.apply(this, arguments);
/**
The array of client ids backing the record array. When a
record is requested from the record array, the record
for the client id at the same index is materialized, if
necessary, by the store.
@property content
@private
@type Ember.Array
*/
this.set('content', this.content || null);
/**
The flag to signal a `RecordArray` is finished loading data.
Example
```javascript
var people = store.peekAll('person');
people.get('isLoaded'); // true
```
@property isLoaded
@type Boolean
*/
this.isLoaded = this.isLoaded || false;
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.peekAll('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@property isUpdating
@type Boolean
*/
this.isUpdating = false;
/**
The store that created this record array.
@property store
@private
@type DS.Store
*/
this.store = this.store || null;
this._updatingPromise = null;
},
replace: function () {
throw new Error("The result of a server query (for all " + this.modelName + " types) is immutable. To modify contents, use toArray()");
},
/**
The modelClass represented by this record array.
@property type
@type DS.Model
*/
type: computed('modelName', function () {
if (!this.modelName) {
return null;
}
return this.store._modelFor(this.modelName);
}).readOnly(),
/**
Retrieves an object from the content by index.
@method objectAtContent
@private
@param {Number} index
@return {DS.Model} record
*/
objectAtContent: function (index) {
var internalModel = get(this, 'content').objectAt(index);
return internalModel && internalModel.getRecord();
},
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
var people = store.peekAll('person');
people.get('isUpdating'); // false
people.update().then(function() {
people.get('isUpdating'); // false
});
people.get('isUpdating'); // true
```
@method update
*/
update: function () {
var _this = this;
if (get(this, 'isUpdating')) {
return this._updatingPromise;
}
this.set('isUpdating', true);
var updatingPromise = this._update().finally(function () {
_this._updatingPromise = null;
if (_this.get('isDestroying') || _this.get('isDestroyed')) {
return;
}
_this.set('isUpdating', false);
});
this._updatingPromise = updatingPromise;
return updatingPromise;
},
/*
Update this RecordArray and return a promise which resolves once the update
is finished.
*/
_update: function () {
return this.store.findAll(this.modelName, { reload: true });
},
/**
Adds an internal model to the `RecordArray` without duplicates
@method _pushInternalModels
@private
@param {InternalModel} internalModel
*/
_pushInternalModels: function (internalModels) {
// pushObjects because the internalModels._recordArrays set was already
// consulted for inclusion, so addObject and its on .contains call is not
// required.
get(this, 'content').pushObjects(internalModels);
},
/**
Removes an internalModel to the `RecordArray`.
@method removeInternalModel
@private
@param {InternalModel} internalModel
*/
_removeInternalModels: function (internalModels) {
get(this, 'content').removeObjects(internalModels);
},
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
var messages = store.peekAll('message');
messages.forEach(function(message) {
message.set('hasBeenSeen', true);
});
messages.save();
```
@method save
@return {DS.PromiseArray} promise
*/
save: function () {
var _this2 = this;
var promiseLabel = "DS: RecordArray#save " + this.modelName;
var promise = Promise.all(this.invoke('save'), promiseLabel).then(function () {
return _this2;
}, null, 'DS: RecordArray#save return RecordArray');
return _promiseProxies.PromiseArray.create({ promise: promise });
},
_dissociateFromOwnRecords: function () {
var _this3 = this;
this.get('content').forEach(function (internalModel) {
var recordArrays = internalModel.__recordArrays;
if (recordArrays) {
recordArrays.delete(_this3);
}
});
},
/**
@method _unregisterFromManager
@private
*/
_unregisterFromManager: function () {
this.manager.unregisterRecordArray(this);
},
willDestroy: function () {
this._unregisterFromManager();
this._dissociateFromOwnRecords();
// TODO: we should not do work during destroy:
// * when objects are destroyed, they should simply be left to do
// * if logic errors do to this, that logic needs to be more careful during
// teardown (ember provides isDestroying/isDestroyed) for this reason
// * the exception being: if an dominator has a reference to this object,
// and must be informed to release e.g. e.g. removing itself from th
// recordArrayMananger
set(this, 'content', null);
set(this, 'length', 0);
this._super.apply(this, arguments);
},
/*
@method _createSnapshot
@private
*/
_createSnapshot: function (options) {
// this is private for users, but public for ember-data internals
return new _snapshotRecordArray.default(this, this.get('meta'), options);
},
/*
@method _takeSnapshot
@private
*/
_takeSnapshot: function () {
return get(this, 'content').map(function (internalModel) {
return internalModel.createSnapshot();
});
}
});
});
define('ember-data/-private/system/references', ['exports', 'ember-data/-private/system/references/record', 'ember-data/-private/system/references/belongs-to', 'ember-data/-private/system/references/has-many'], function (exports, _record, _belongsTo, _hasMany) {
'use strict';
exports.__esModule = true;
exports.HasManyReference = exports.BelongsToReference = exports.RecordReference = undefined;
exports.RecordReference = _record.default;
exports.BelongsToReference = _belongsTo.default;
exports.HasManyReference = _hasMany.default;
});
define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/-private/system/model/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/features', 'ember-data/-debug'], function (exports, _model, _ember, _reference, _features, _debug) {
'use strict';
exports.__esModule = true;
/**
A BelongsToReference is a low level API that allows users and
addon author to perform meta-operations on a belongs-to
relationship.
@class BelongsToReference
@namespace DS
@extends DS.Reference
*/
var BelongsToReference = function (store, parentInternalModel, belongsToRelationship) {
this._super$constructor(store, parentInternalModel);
this.belongsToRelationship = belongsToRelationship;
this.type = belongsToRelationship.relationshipMeta.type;
this.parent = parentInternalModel.recordReference;
// TODO inverse
};
BelongsToReference.prototype = Object.create(_reference.default.prototype);
BelongsToReference.prototype.constructor = BelongsToReference;
BelongsToReference.prototype._super$constructor = _reference.default;
/**
This returns a string that represents how the reference will be
looked up when it is loaded. If the relationship has a link it will
use the "link" otherwise it defaults to "id".
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
});
let userRef = blog.belongsTo('user');
// get the identifier of the reference
if (userRef.remoteType() === "id") {
let id = userRef.id();
} else if (userRef.remoteType() === "link") {
let link = userRef.link();
}
```
@method remoteType
@return {String} The name of the remote type. This should either be "link" or "id"
*/
BelongsToReference.prototype.remoteType = function () {
if (this.belongsToRelationship.link) {
return "link";
}
return "id";
};
/**
The `id` of the record that this reference refers to. Together, the
`type()` and `id()` methods form a composite key for the identity
map. This can be used to access the id of an async relationship
without triggering a fetch that would normally happen if you
attempted to use `record.get('relationship.id')`.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
// get the identifier of the reference
if (userRef.remoteType() === "id") {
let id = userRef.id();
}
```
@method id
@return {String} The id of the record in this belongsTo relationship.
*/
BelongsToReference.prototype.id = function () {
var inverseInternalModel = this.belongsToRelationship.inverseInternalModel;
return inverseInternalModel && inverseInternalModel.id;
};
/**
The link Ember Data will use to fetch or reload this belongs-to
relationship.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
links: {
related: '/articles/1/author'
}
}
}
}
});
let userRef = blog.belongsTo('user');
// get the identifier of the reference
if (userRef.remoteType() === "link") {
let link = userRef.link();
}
```
@method link
@return {String} The link Ember Data will use to fetch or reload this belongs-to relationship.
*/
BelongsToReference.prototype.link = function () {
return this.belongsToRelationship.link;
};
/**
The meta data for the belongs-to relationship.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
links: {
related: {
href: '/articles/1/author',
meta: {
lastUpdated: 1458014400000
}
}
}
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.meta() // { lastUpdated: 1458014400000 }
```
@method meta
@return {Object} The meta information for the belongs-to relationship.
*/
BelongsToReference.prototype.meta = function () {
return this.belongsToRelationship.meta;
};
/**
`push` can be used to update the data in the relationship and Ember
Data will treat the new data as the conanical value of this
relationship on the backend.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
// provide data for reference
userRef.push({
data: {
type: 'user',
id: 1,
attributes: {
username: "@user"
}
}
}).then(function(user) {
userRef.value() === user;
});
```
@method push
@param {Object|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship.
@return {Promise<record>} A promise that resolves with the new value in this belongs-to relationship.
*/
BelongsToReference.prototype.push = function (objectOrPromise) {
var _this = this;
return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) {
var record = void 0;
if (data instanceof _model.default) {
if ((0, _features.default)('ds-overhaul-references')) {
(false && !(false) && _ember.default.deprecate("BelongsToReference#push(DS.Model) is deprecated. Update relationship via `model.set('relationshipName', value)` instead.", false, {
id: 'ds.references.belongs-to.push-record',
until: '3.0'
}));
}
record = data;
} else {
record = _this.store.push(data);
}
(0, _debug.assertPolymorphicType)(_this.internalModel, _this.belongsToRelationship.relationshipMeta, record._internalModel);
_this.belongsToRelationship.setCanonicalInternalModel(record._internalModel);
return record;
});
};
/**
`value()` synchronously returns the current value of the belongs-to
relationship. Unlike `record.get('relationshipName')`, calling
`value()` on a reference does not trigger a fetch if the async
relationship is not yet loaded. If the relationship is not loaded
it will always return `null`.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.value(); // null
// provide data for reference
userRef.push({
data: {
type: 'user',
id: 1,
attributes: {
username: "@user"
}
}
}).then(function(user) {
userRef.value(); // user
});
```
@method value
@param {Object|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship.
@return {DS.Model} the record in this relationship
*/
BelongsToReference.prototype.value = function () {
var inverseInternalModel = this.belongsToRelationship.inverseInternalModel;
if (inverseInternalModel && inverseInternalModel.isLoaded()) {
return inverseInternalModel.getRecord();
}
return null;
};
/**
Loads a record in a belongs to relationship if it is not already
loaded. If the relationship is already loaded this method does not
trigger a new load.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.value(); // null
userRef.load().then(function(user) {
userRef.value() === user
});
@method load
@return {Promise} a promise that resolves with the record in this belongs-to relationship.
*/
BelongsToReference.prototype.load = function () {
var _this2 = this;
if (this.remoteType() === "id") {
return this.belongsToRelationship.getRecord();
}
if (this.remoteType() === "link") {
return this.belongsToRelationship.findLink().then(function (internalModel) {
return _this2.value();
});
}
};
/**
Triggers a reload of the value in this relationship. If the
remoteType is `"link"` Ember Data will use the relationship link to
reload the relationship. Otherwise it will reload the record by its
id.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.reload().then(function(user) {
userRef.value() === user
});
@method reload
@return {Promise} a promise that resolves with the record in this belongs-to relationship after the reload has completed.
*/
BelongsToReference.prototype.reload = function () {
var _this3 = this;
return this.belongsToRelationship.reload().then(function (internalModel) {
return _this3.value();
});
};
exports.default = BelongsToReference;
});
define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-debug', 'ember-data/-private/features'], function (exports, _ember, _reference, _debug, _features) {
'use strict';
exports.__esModule = true;
var resolve = _ember.default.RSVP.resolve,
get = _ember.default.get;
/**
A HasManyReference is a low level API that allows users and addon
author to perform meta-operations on a has-many relationship.
@class HasManyReference
@namespace DS
*/
var HasManyReference = function (store, parentInternalModel, hasManyRelationship) {
this._super$constructor(store, parentInternalModel);
this.hasManyRelationship = hasManyRelationship;
this.type = hasManyRelationship.relationshipMeta.type;
this.parent = parentInternalModel.recordReference;
// TODO inverse
};
HasManyReference.prototype = Object.create(_reference.default.prototype);
HasManyReference.prototype.constructor = HasManyReference;
HasManyReference.prototype._super$constructor = _reference.default;
/**
This returns a string that represents how the reference will be
looked up when it is loaded. If the relationship has a link it will
use the "link" otherwise it defaults to "id".
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
// get the identifier of the reference
if (commentsRef.remoteType() === "ids") {
let ids = commentsRef.ids();
} else if (commentsRef.remoteType() === "link") {
let link = commentsRef.link();
}
```
@method remoteType
@return {String} The name of the remote type. This should either be "link" or "ids"
*/
HasManyReference.prototype.remoteType = function () {
if (this.hasManyRelationship.link) {
return "link";
}
return "ids";
};
/**
The link Ember Data will use to fetch or reload this has-many
relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
links: {
related: '/posts/1/comments'
}
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.link(); // '/posts/1/comments'
```
@method link
@return {String} The link Ember Data will use to fetch or reload this has-many relationship.
*/
HasManyReference.prototype.link = function () {
return this.hasManyRelationship.link;
};
/**
`ids()` returns an array of the record ids in this relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.ids(); // ['1']
```
@method ids
@return {Array} The ids in this has-many relationship
*/
HasManyReference.prototype.ids = function () {
var members = this.hasManyRelationship.members.toArray();
return members.map(function (internalModel) {
return internalModel.id;
});
};
/**
The meta data for the has-many relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
links: {
related: {
href: '/posts/1/comments',
meta: {
count: 10
}
}
}
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.meta(); // { count: 10 }
```
@method meta
@return {Object} The meta information for the has-many relationship.
*/
HasManyReference.prototype.meta = function () {
return this.hasManyRelationship.meta;
};
/**
`push` can be used to update the data in the relationship and Ember
Data will treat the new data as the canonical value of this
relationship on the backend.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.ids(); // ['1']
commentsRef.push([
[{ type: 'comment', id: 2 }],
[{ type: 'comment', id: 3 }],
])
commentsRef.ids(); // ['2', '3']
```
@method push
@param {Array|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship.
@return {DS.ManyArray}
*/
HasManyReference.prototype.push = function (objectOrPromise) {
var _this = this;
return resolve(objectOrPromise).then(function (payload) {
var array = payload;
if ((0, _features.default)("ds-overhaul-references")) {
(false && !(!Array.isArray(payload)) && _ember.default.deprecate("HasManyReference#push(array) is deprecated. Push a JSON-API document instead.", !Array.isArray(payload), {
id: 'ds.references.has-many.push-array',
until: '3.0'
}));
}
var useLegacyArrayPush = true;
if (typeof payload === "object" && payload.data) {
array = payload.data;
useLegacyArrayPush = array.length && array[0].data;
if ((0, _features.default)('ds-overhaul-references')) {
(false && !(!useLegacyArrayPush) && _ember.default.deprecate("HasManyReference#push() expects a valid JSON-API document.", !useLegacyArrayPush, {
id: 'ds.references.has-many.push-invalid-json-api',
until: '3.0'
}));
}
}
if (!(0, _features.default)('ds-overhaul-references')) {
useLegacyArrayPush = true;
}
var internalModels = void 0;
if (useLegacyArrayPush) {
internalModels = array.map(function (obj) {
var record = _this.store.push(obj);
if (false) {
var relationshipMeta = _this.hasManyRelationship.relationshipMeta;
(0, _debug.assertPolymorphicType)(_this.internalModel, relationshipMeta, record._internalModel);
}
return record._internalModel;
});
} else {
var records = _this.store.push(payload);
internalModels = _ember.default.A(records).mapBy('_internalModel');
if (false) {
internalModels.forEach(function (internalModel) {
var relationshipMeta = _this.hasManyRelationship.relationshipMeta;
(0, _debug.assertPolymorphicType)(_this.internalModel, relationshipMeta, internalModel);
});
}
}
_this.hasManyRelationship.computeChanges(internalModels);
return _this.hasManyRelationship.manyArray;
});
};
HasManyReference.prototype._isLoaded = function () {
var hasData = get(this.hasManyRelationship, 'hasData');
if (!hasData) {
return false;
}
var members = this.hasManyRelationship.members.toArray();
return members.every(function (internalModel) {
return internalModel.isLoaded() === true;
});
};
/**
`value()` sycronously returns the current value of the has-many
relationship. Unlike `record.get('relationshipName')`, calling
`value()` on a reference does not trigger a fetch if the async
relationship is not yet loaded. If the relationship is not loaded
it will always return `null`.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
post.get('comments').then(function(comments) {
commentsRef.value() === comments
})
```
@method value
@return {DS.ManyArray}
*/
HasManyReference.prototype.value = function () {
if (this._isLoaded()) {
return this.hasManyRelationship.manyArray;
}
return null;
};
/**
Loads the relationship if it is not already loaded. If the
relationship is already loaded this method does not trigger a new
load.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.load().then(function(comments) {
//...
});
```
@method load
@return {Promise} a promise that resolves with the ManyArray in
this has-many relationship.
*/
HasManyReference.prototype.load = function () {
if (!this._isLoaded()) {
return this.hasManyRelationship.getRecords();
}
return resolve(this.hasManyRelationship.manyArray);
};
/**
Reloads this has-many relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.reload().then(function(comments) {
//...
});
```
@method reload
@return {Promise} a promise that resolves with the ManyArray in this has-many relationship.
*/
HasManyReference.prototype.reload = function () {
return this.hasManyRelationship.reload();
};
exports.default = HasManyReference;
});
define('ember-data/-private/system/references/record', ['exports', 'ember', 'ember-data/-private/system/references/reference'], function (exports, _ember, _reference) {
'use strict';
exports.__esModule = true;
/**
An RecordReference is a low level API that allows users and
addon author to perform meta-operations on a record.
@class RecordReference
@namespace DS
*/
var RecordReference = function (store, internalModel) {
this._super$constructor(store, internalModel);
this.type = internalModel.modelName;
this._id = internalModel.id;
};
RecordReference.prototype = Object.create(_reference.default.prototype);
RecordReference.prototype.constructor = RecordReference;
RecordReference.prototype._super$constructor = _reference.default;
/**
The `id` of the record that this reference refers to.
Together, the `type` and `id` properties form a composite key for
the identity map.
Example
```javascript
let userRef = store.getReference('user', 1);
userRef.id(); // '1'
```
@method id
@return {String} The id of the record.
*/
RecordReference.prototype.id = function () {
return this._id;
};
/**
How the reference will be looked up when it is loaded: Currently
this always return `identity` to signifying that a record will be
loaded by the `type` and `id`.
Example
```javascript
const userRef = store.getReference('user', 1);
userRef.remoteType(); // 'identity'
```
@method remoteType
@return {String} 'identity'
*/
RecordReference.prototype.remoteType = function () {
return 'identity';
};
/**
This API allows you to provide a reference with new data. The
simplest usage of this API is similar to `store.push`: you provide a
normalized hash of data and the object represented by the reference
will update.
If you pass a promise to `push`, Ember Data will not ask the adapter
for the data if another attempt to fetch it is made in the
interim. When the promise resolves, the underlying object is updated
with the new data, and the promise returned by *this function* is resolved
with that object.
For example, `recordReference.push(promise)` will be resolved with a
record.
Example
```javascript
let userRef = store.getReference('user', 1);
// provide data for reference
userRef.push({ data: { id: 1, username: "@user" }}).then(function(user) {
userRef.value() === user;
});
```
@method push
@param {Promise|Object}
@return Promise<record> a promise for the value (record or relationship)
*/
RecordReference.prototype.push = function (objectOrPromise) {
var _this = this;
return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) {
return _this.store.push(data);
});
};
/**
If the entity referred to by the reference is already loaded, it is
present as `reference.value`. Otherwise the value returned by this function
is `null`.
Example
```javascript
let userRef = store.getReference('user', 1);
userRef.value(); // user
```
@method value
@return {DS.Model} the record for this RecordReference
*/
RecordReference.prototype.value = function () {
if (this.internalModel.hasRecord) {
return this.internalModel.getRecord();
}
};
/**
Triggers a fetch for the backing entity based on its `remoteType`
(see `remoteType` definitions per reference type).
Example
```javascript
let userRef = store.getReference('user', 1);
// load user (via store.find)
userRef.load().then(...)
```
@method load
@return {Promise<record>} the record for this RecordReference
*/
RecordReference.prototype.load = function () {
return this.store.findRecord(this.type, this._id);
};
/**
Reloads the record if it is already loaded. If the record is not
loaded it will load the record via `store.findRecord`
Example
```javascript
let userRef = store.getReference('user', 1);
// or trigger a reload
userRef.reload().then(...)
```
@method reload
@return {Promise<record>} the record for this RecordReference
*/
RecordReference.prototype.reload = function () {
var record = this.value();
if (record) {
return record.reload();
}
return this.load();
};
exports.default = RecordReference;
});
define("ember-data/-private/system/references/reference", ["exports"], function (exports) {
"use strict";
exports.__esModule = true;
var Reference = function (store, internalModel) {
this.store = store;
this.internalModel = internalModel;
};
Reference.prototype = {
constructor: Reference
};
exports.default = Reference;
});
define('ember-data/-private/system/relationship-meta', ['exports', 'ember-inflector', 'ember-data/-private/system/normalize-model-name'], function (exports, _emberInflector, _normalizeModelName) {
'use strict';
exports.__esModule = true;
exports.typeForRelationshipMeta = typeForRelationshipMeta;
exports.relationshipFromMeta = relationshipFromMeta;
function typeForRelationshipMeta(meta) {
var modelName = void 0;
modelName = meta.type || meta.key;
if (meta.kind === 'hasMany') {
modelName = (0, _emberInflector.singularize)((0, _normalizeModelName.default)(modelName));
}
return modelName;
}
function relationshipFromMeta(meta) {
var result = {
key: meta.key,
kind: meta.kind,
type: typeForRelationshipMeta(meta),
options: meta.options,
name: meta.name,
parentType: meta.parentType,
isRelationship: true
};
if (false) {
result.parentType = meta.parentType;
}
return result;
}
});
define('ember-data/-private/system/relationships/belongs-to', ['exports', 'ember', 'ember-data/-private/system/normalize-model-name'], function (exports, _ember, _normalizeModelName) {
'use strict';
exports.__esModule = true;
exports.default = belongsTo;
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
profile: DS.belongsTo('profile')
});
```
```app/models/profile.js
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the key name.
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo()
});
```
will lookup for a Post type.
@namespace
@method belongsTo
@for DS
@param {String} modelName (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function belongsTo(modelName, options) {
var opts = void 0,
userEnteredModelName = void 0;
if (typeof modelName === 'object') {
opts = modelName;
userEnteredModelName = undefined;
} else {
opts = options;
userEnteredModelName = modelName;
}
if (typeof userEnteredModelName === 'string') {
userEnteredModelName = (0, _normalizeModelName.default)(userEnteredModelName);
}
(false && _ember.default.assert("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + _ember.default.inspect(userEnteredModelName) + ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", typeof userEnteredModelName === 'string' || typeof userEnteredModelName === 'undefined'));
opts = opts || {};
var meta = {
type: userEnteredModelName,
isRelationship: true,
options: opts,
kind: 'belongsTo',
name: 'Belongs To',
key: null
};
return _ember.default.computed({
get: function (key) {
if (opts.hasOwnProperty('serialize')) {
(false && _ember.default.warn('You provided a serialize option on the "' + key + '" property in the "' + this._internalModel.modelName + '" class, this belongs in the serializer. See DS.Serializer and it\'s implementations http://emberjs.com/api/data/classes/DS.Serializer.html', false, {
id: 'ds.model.serialize-option-in-belongs-to'
}));
}
if (opts.hasOwnProperty('embedded')) {
(false && _ember.default.warn('You provided an embedded option on the "' + key + '" property in the "' + this._internalModel.modelName + '" class, this belongs in the serializer. See DS.EmbeddedRecordsMixin http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html', false, {
id: 'ds.model.embedded-option-in-belongs-to'
}));
}
return this._internalModel._relationships.get(key).getRecord();
},
set: function (key, value) {
if (value === undefined) {
value = null;
}
if (value && value.then) {
this._internalModel._relationships.get(key).setRecordPromise(value);
} else if (value) {
this._internalModel._relationships.get(key).setInternalModel(value._internalModel);
} else {
this._internalModel._relationships.get(key).setInternalModel(value);
}
return this._internalModel._relationships.get(key).getRecord();
}
}).meta(meta);
}
});
define('ember-data/-private/system/relationships/ext', ['exports', 'ember', 'ember-data/-private/system/relationship-meta'], function (exports, _ember, _relationshipMeta) {
'use strict';
exports.__esModule = true;
exports.relationshipsByNameDescriptor = exports.relatedTypesDescriptor = exports.relationshipsDescriptor = undefined;
var Map = _ember.default.Map;
var MapWithDefault = _ember.default.MapWithDefault;
var relationshipsDescriptor = exports.relationshipsDescriptor = _ember.default.computed(function () {
if (_ember.default.testing === true && relationshipsDescriptor._cacheable === true) {
relationshipsDescriptor._cacheable = false;
}
var map = new MapWithDefault({
defaultValue: function () {
return [];
}
});
// Loop through each computed property on the class
this.eachComputedProperty(function (name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
meta.key = name;
var relationshipsForType = map.get((0, _relationshipMeta.typeForRelationshipMeta)(meta));
relationshipsForType.push({
name: name,
kind: meta.kind
});
}
});
return map;
}).readOnly();
var relatedTypesDescriptor = exports.relatedTypesDescriptor = _ember.default.computed(function () {
var _this = this;
if (_ember.default.testing === true && relatedTypesDescriptor._cacheable === true) {
relatedTypesDescriptor._cacheable = false;
}
var modelName = void 0;
var types = _ember.default.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
meta.key = name;
modelName = (0, _relationshipMeta.typeForRelationshipMeta)(meta);
(false && _ember.default.assert('You specified a hasMany (' + meta.type + ') on ' + meta.parentType + ' but ' + meta.type + ' was not found.', modelName));
if (!types.includes(modelName)) {
(false && _ember.default.assert('Trying to sideload ' + name + ' on ' + _this.toString() + ' but the type doesn\'t exist.', !!modelName));
types.push(modelName);
}
}
});
return types;
}).readOnly();
var relationshipsByNameDescriptor = exports.relationshipsByNameDescriptor = _ember.default.computed(function () {
var map = Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
meta.key = name;
var relationship = (0, _relationshipMeta.relationshipFromMeta)(meta);
relationship.type = (0, _relationshipMeta.typeForRelationshipMeta)(meta);
map.set(name, relationship);
}
});
return map;
}).readOnly();
});
define('ember-data/-private/system/relationships/has-many', ['exports', 'ember', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/system/is-array-like'], function (exports, _ember, _normalizeModelName, _isArrayLike) {
'use strict';
exports.__esModule = true;
exports.default = hasMany;
var get = _ember.default.get;
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
tags: DS.hasMany('tag')
});
```
```app/models/tag.js
import DS from 'ember-data';
export default DS.Model.extend({
posts: DS.hasMany('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the singularized key name.
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
tags: DS.hasMany()
});
```
will lookup for a Tag type.
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasMany` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
onePost: DS.belongsTo('post'),
twoPost: DS.belongsTo('post'),
redPost: DS.belongsTo('post'),
bluePost: DS.belongsTo('post')
});
```
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String} type (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function hasMany(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
}
(false && _ember.default.assert('The first argument to DS.hasMany must be a string representing a model type key, not an instance of ' + _ember.default.inspect(type) + '. E.g., to define a relation to the Comment model, use DS.hasMany(\'comment\')', typeof type === 'string' || typeof type === 'undefined'));
options = options || {};
if (typeof type === 'string') {
type = (0, _normalizeModelName.default)(type);
}
// Metadata about relationships is stored on the meta of
// the relationship. This is used for introspection and
// serialization. Note that `key` is populated lazily
// the first time the CP is called.
var meta = {
type: type,
options: options,
isRelationship: true,
kind: 'hasMany',
name: 'Has Many',
key: null
};
return _ember.default.computed({
get: function (key) {
return this._internalModel._relationships.get(key).getRecords();
},
set: function (key, records) {
(false && _ember.default.assert('You must pass an array of records to set a hasMany relationship', (0, _isArrayLike.default)(records)));
(false && _ember.default.assert('All elements of a hasMany relationship must be instances of DS.Model, you passed ' + _ember.default.inspect(records), function () {
return _ember.default.A(records).every(function (record) {
return record.hasOwnProperty('_internalModel') === true;
});
}()));
var relationship = this._internalModel._relationships.get(key);
relationship.clear();
relationship.addInternalModels(records.map(function (record) {
return get(record, '_internalModel');
}));
return relationship.getRecords();
}
}).meta(meta);
}
});
define('ember-data/-private/system/relationships/relationship-payloads-manager', ['exports', 'ember', 'ember-data/-private/system/relationships/relationship-payloads'], function (exports, _ember, _relationshipPayloads) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _get = _ember.default.get;
/**
Manages relationship payloads for a given store, for uninitialized
relationships. Acts as a single source of truth (of payloads) for both sides
of an uninitialized relationship so they can agree on the most up-to-date
payload received without needing too much eager processing when those payloads
are pushed into the store.
This minimizes the work spent on relationships that are never initialized.
Once relationships are initialized, their state is managed in a relationship
state object (eg BelongsToRelationship or ManyRelationship).
@example
let relationshipPayloadsManager = new RelationshipPayloadsManager(store);
const User = DS.Model.extend({
hobbies: DS.hasMany('hobby')
});
const Hobby = DS.Model.extend({
user: DS.belongsTo('user')
});
let userPayload = {
data: {
id: 1,
type: 'user',
relationships: {
hobbies: {
data: [{
id: 2,
type: 'hobby'
}]
}
}
},
};
relationshipPayloadsManager.push('user', 1, userPayload.data.relationships);
relationshipPayloadsManager.get('hobby', 2, 'user') === {
{
data: {
id: 1,
type: 'user'
}
}
}
@private
@class RelationshipPayloadsManager
*/
var RelationshipPayloadsManager = function () {
function RelationshipPayloadsManager(store) {
_classCallCheck(this, RelationshipPayloadsManager);
this._store = store;
// cache of `RelationshipPayload`s
this._cache = Object.create(null);
}
/**
Find the payload for the given relationship of the given model.
Returns the payload for the given relationship, whether raw or computed from
the payload of the inverse relationship.
@example
relationshipPayloadsManager.get('hobby', 2, 'user') === {
{
data: {
id: 1,
type: 'user'
}
}
}
@method
*/
RelationshipPayloadsManager.prototype.get = function get(modelName, id, relationshipName) {
var modelClass = this._store._modelFor(modelName);
var relationshipsByName = _get(modelClass, 'relationshipsByName');
var relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName, false);
return relationshipPayloads && relationshipPayloads.get(modelName, id, relationshipName);
};
RelationshipPayloadsManager.prototype.push = function push(modelName, id, relationshipsData) {
var _this = this;
if (!relationshipsData) {
return;
}
var modelClass = this._store._modelFor(modelName);
var relationshipsByName = _get(modelClass, 'relationshipsByName');
Object.keys(relationshipsData).forEach(function (key) {
var relationshipPayloads = _this._getRelationshipPayloads(modelName, key, modelClass, relationshipsByName, true);
if (relationshipPayloads) {
relationshipPayloads.push(modelName, id, key, relationshipsData[key]);
}
});
};
RelationshipPayloadsManager.prototype.unload = function unload(modelName, id) {
var _this2 = this;
var modelClass = this._store._modelFor(modelName);
var relationshipsByName = _get(modelClass, 'relationshipsByName');
relationshipsByName.forEach(function (_, relationshipName) {
var relationshipPayloads = _this2._getRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName, false);
if (relationshipPayloads) {
relationshipPayloads.unload(modelName, id, relationshipName);
}
});
};
RelationshipPayloadsManager.prototype._getRelationshipPayloads = function _getRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName, init) {
if (!relationshipsByName.has(relationshipName)) {
return;
}
var key = modelName + ':' + relationshipName;
if (!this._cache[key] && init) {
return this._initializeRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName);
}
return this._cache[key];
};
RelationshipPayloadsManager.prototype._initializeRelationshipPayloads = function _initializeRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName) {
var relationshipMeta = relationshipsByName.get(relationshipName);
var inverseMeta = modelClass.inverseFor(relationshipName, this._store);
var inverseModelName = void 0;
var inverseRelationshipName = void 0;
var inverseRelationshipMeta = void 0;
// figure out the inverse relationship; we need two things
// a) the inverse model name
//- b) the name of the inverse relationship
if (inverseMeta) {
inverseRelationshipName = inverseMeta.name;
inverseModelName = relationshipMeta.type;
inverseRelationshipMeta = _get(inverseMeta.type, 'relationshipsByName').get(inverseRelationshipName);
} else {
// relationship has no inverse
inverseModelName = inverseRelationshipName = '';
inverseRelationshipMeta = null;
}
var lhsKey = modelName + ':' + relationshipName;
var rhsKey = inverseModelName + ':' + inverseRelationshipName;
// populate the cache for both sides of the relationship, as they both use
// the same `RelationshipPayloads`.
//
// This works out better than creating a single common key, because to
// compute that key we would need to do work to look up the inverse
//
return this._cache[lhsKey] = this._cache[rhsKey] = new _relationshipPayloads.default(this._store, modelName, relationshipName, relationshipMeta, inverseModelName, inverseRelationshipName, inverseRelationshipMeta);
};
return RelationshipPayloadsManager;
}();
exports.default = RelationshipPayloadsManager;
});
define('ember-data/-private/system/relationships/relationship-payloads', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _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 RelationshipPayloads = function () {
function RelationshipPayloads(store, modelName, relationshipName, relationshipMeta, inverseModelName, inverseRelationshipName, inverseRelationshipMeta) {
_classCallCheck(this, RelationshipPayloads);
this._store = store;
this._lhsModelName = modelName;
this._lhsRelationshipName = relationshipName;
this._lhsRelationshipMeta = relationshipMeta;
this._rhsModelName = inverseModelName;
this._rhsRelationshipName = inverseRelationshipName;
this._rhsRelationshipMeta = inverseRelationshipMeta;
// a map of id -> payloads for the left hand side of the relationship.
this._lhsPayloads = Object.create(null);
if (modelName !== inverseModelName || relationshipName !== inverseRelationshipName) {
// The common case of a non-reflexive relationship, or a reflexive
// relationship whose inverse is not itself
this._rhsPayloads = Object.create(null);
this._isReflexive = false;
} else {
// Edge case when we have a reflexive relationship to itself
// eg user hasMany friends inverse friends
//
// In this case there aren't really two sides to the relationship, but
// we set `_rhsPayloads = _lhsPayloads` to make things easier to reason
// about
this._rhsPayloads = this._lhsPayloads;
this._isReflexive = true;
}
// When we push relationship payloads, just stash them in a queue until
// somebody actually asks for one of them.
//
// This is a queue of the relationship payloads that have been pushed for
// either side of this relationship
this._pendingPayloads = [];
}
/**
Get the payload for the relationship of an individual record.
This might return the raw payload as pushed into the store, or one computed
from the payload of the inverse relationship.
@method
*/
RelationshipPayloads.prototype.get = function get(modelName, id, relationshipName) {
this._flushPending();
if (this._isLHS(modelName, relationshipName)) {
return this._lhsPayloads[id];
} else {
(false && Ember.assert(modelName + ':' + relationshipName + ' is not either side of this relationship, ' + this._lhsModelName + ':' + this._lhsRelationshipName + '<->' + this._rhsModelName + ':' + this._rhsRelationshipName, this._isRHS(modelName, relationshipName)));
return this._rhsPayloads[id];
}
};
RelationshipPayloads.prototype.push = function push(modelName, id, relationshipName, relationshipData) {
this._pendingPayloads.push([modelName, id, relationshipName, relationshipData]);
};
RelationshipPayloads.prototype.unload = function unload(modelName, id, relationshipName) {
this._flushPending();
if (this._isLHS(modelName, relationshipName)) {
delete this._lhsPayloads[id];
} else {
(false && Ember.assert(modelName + ':' + relationshipName + ' is not either side of this relationship, ' + this._lhsModelName + ':' + this._lhsRelationshipName + '<->' + this._rhsModelName + ':' + this._rhsRelationshipName, this._isRHS(modelName, relationshipName)));
delete this._rhsPayloads[id];
}
};
RelationshipPayloads.prototype._isLHS = function _isLHS(modelName, relationshipName) {
return modelName === this._lhsModelName && relationshipName === this._lhsRelationshipName;
};
RelationshipPayloads.prototype._isRHS = function _isRHS(modelName, relationshipName) {
return modelName === this._rhsModelName && relationshipName === this._rhsRelationshipName;
};
RelationshipPayloads.prototype._flushPending = function _flushPending() {
if (this._pendingPayloads.length === 0) {
return;
}
var payloadsToBeProcessed = this._pendingPayloads.splice(0, this._pendingPayloads.length);
for (var i = 0; i < payloadsToBeProcessed.length; ++i) {
var modelName = payloadsToBeProcessed[i][0];
var id = payloadsToBeProcessed[i][1];
var relationshipName = payloadsToBeProcessed[i][2];
var relationshipData = payloadsToBeProcessed[i][3];
// TODO: maybe delay this allocation slightly?
var inverseRelationshipData = {
data: {
id: id,
type: modelName
}
// start flushing this individual payload. The logic is the same whether
// it's for the left hand side of the relationship or the right hand side,
// except the role of primary and inverse idToPayloads is reversed
//
};var previousPayload = void 0;
var idToPayloads = void 0;
var inverseIdToPayloads = void 0;
var inverseIsMany = void 0;
if (this._isLHS(modelName, relationshipName)) {
previousPayload = this._lhsPayloads[id];
idToPayloads = this._lhsPayloads;
inverseIdToPayloads = this._rhsPayloads;
inverseIsMany = this._rhsRelationshipIsMany;
} else {
(false && Ember.assert(modelName + ':' + relationshipName + ' is not either side of this relationship, ' + this._lhsModelName + ':' + this._lhsRelationshipName + '<->' + this._rhsModelName + ':' + this._rhsRelationshipName, this._isRHS(modelName, relationshipName)));
previousPayload = this._rhsPayloads[id];
idToPayloads = this._rhsPayloads;
inverseIdToPayloads = this._lhsPayloads;
inverseIsMany = this._lhsRelationshipIsMany;
}
// actually flush this individual payload
//
// We remove the previous inverse before populating our current one
// because we may have multiple payloads for the same relationship, in
// which case the last one wins.
//
// eg if user hasMany helicopters, and helicopter belongsTo user and we see
//
// [{
// data: {
// id: 1,
// type: 'helicopter',
// relationships: {
// user: {
// id: 2,
// type: 'user'
// }
// }
// }
// }, {
// data: {
// id: 1,
// type: 'helicopter',
// relationships: {
// user: {
// id: 4,
// type: 'user'
// }
// }
// }
// }]
//
// Then we will initially have set user:2 as having helicopter:1, which we
// need to remove before adding helicopter:1 to user:4
//
this._removeInverse(id, previousPayload, inverseIdToPayloads);
idToPayloads[id] = relationshipData;
this._populateInverse(relationshipData, inverseRelationshipData, inverseIdToPayloads, inverseIsMany);
}
};
RelationshipPayloads.prototype._populateInverse = function _populateInverse(relationshipData, inversePayload, inverseIdToPayloads, inverseIsMany) {
if (!relationshipData.data) {
// This id doesn't have an inverse, eg a belongsTo with a payload
// { data: null }, so there's nothing to populate
return;
}
if (Array.isArray(relationshipData.data)) {
for (var i = 0; i < relationshipData.data.length; ++i) {
var inverseId = relationshipData.data[i].id;
this._addToInverse(inversePayload, inverseId, inverseIdToPayloads, inverseIsMany);
}
} else {
var _inverseId = relationshipData.data.id;
this._addToInverse(inversePayload, _inverseId, inverseIdToPayloads, inverseIsMany);
}
};
RelationshipPayloads.prototype._addToInverse = function _addToInverse(inversePayload, inverseId, inverseIdToPayloads, inverseIsMany) {
if (this._isReflexive && inversePayload.data.id === inverseId) {
// eg <user:1>.friends = [{ id: 1, type: 'user' }]
return;
}
var existingPayload = inverseIdToPayloads[inverseId];
var existingData = existingPayload && existingPayload.data;
if (existingData) {
// There already is an inverse, either add or overwrite depehnding on
// whether the inverse is a many relationship or not
//
if (Array.isArray(existingData)) {
existingData.push(inversePayload.data);
} else {
inverseIdToPayloads[inverseId] = inversePayload;
}
} else {
// first time we're populating the inverse side
//
if (inverseIsMany) {
inverseIdToPayloads[inverseId] = {
data: [inversePayload.data]
};
} else {
inverseIdToPayloads[inverseId] = inversePayload;
}
}
};
RelationshipPayloads.prototype._removeInverse = function _removeInverse(id, previousPayload, inverseIdToPayloads) {
var data = previousPayload && previousPayload.data;
if (!data) {
// either this is the first time we've seen a payload for this id, or its
// previous payload indicated that it had no inverse, eg a belongsTo
// relationship with payload { data: null }
//
// In either case there's nothing that needs to be removed from the
// inverse map of payloads
return;
}
if (Array.isArray(data)) {
// TODO: diff rather than removeall addall?
for (var i = 0; i < data.length; ++i) {
this._removeFromInverse(id, data[i].id, inverseIdToPayloads);
}
} else {
this._removeFromInverse(id, data.id, inverseIdToPayloads);
}
};
RelationshipPayloads.prototype._removeFromInverse = function _removeFromInverse(id, inverseId, inversePayloads) {
var inversePayload = inversePayloads[inverseId];
var data = inversePayload && inversePayload.data;
if (!data) {
return;
}
if (Array.isArray(data)) {
inversePayload.data = data.filter(function (x) {
return x.id !== id;
});
} else {
inversePayloads[inverseId] = {
data: null
};
}
};
_createClass(RelationshipPayloads, [{
key: '_lhsRelationshipIsMany',
get: function () {
return this._lhsRelationshipMeta && this._lhsRelationshipMeta.kind === 'hasMany';
}
}, {
key: '_rhsRelationshipIsMany',
get: function () {
return this._rhsRelationshipMeta && this._rhsRelationshipMeta.kind === 'hasMany';
}
}]);
return RelationshipPayloads;
}();
exports.default = RelationshipPayloads;
});
define('ember-data/-private/system/relationships/state/belongs-to', ['exports', 'ember', 'ember-data/-debug', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/relationships/state/relationship'], function (exports, _ember, _debug, _promiseProxies, _relationship) {
'use strict';
exports.__esModule = true;
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 BelongsToRelationship = function (_Relationship) {
_inherits(BelongsToRelationship, _Relationship);
function BelongsToRelationship(store, internalModel, inverseKey, relationshipMeta) {
_classCallCheck(this, BelongsToRelationship);
var _this = _possibleConstructorReturn(this, _Relationship.call(this, store, internalModel, inverseKey, relationshipMeta));
_this.internalModel = internalModel;
_this.key = relationshipMeta.key;
_this.inverseInternalModel = null;
_this.canonicalState = null;
return _this;
}
BelongsToRelationship.prototype.setInternalModel = function setInternalModel(internalModel) {
if (internalModel) {
this.addInternalModel(internalModel);
} else if (this.inverseInternalModel) {
this.removeInternalModel(this.inverseInternalModel);
}
this.setHasData(true);
this.setHasLoaded(true);
};
BelongsToRelationship.prototype.setCanonicalInternalModel = function setCanonicalInternalModel(internalModel) {
if (internalModel) {
this.addCanonicalInternalModel(internalModel);
} else if (this.canonicalState) {
this.removeCanonicalInternalModel(this.canonicalState);
}
this.flushCanonicalLater();
};
BelongsToRelationship.prototype.setInitialCanonicalInternalModel = function setInitialCanonicalInternalModel(internalModel) {
if (!internalModel) {
return;
}
// When we initialize a belongsTo relationship, we want to avoid work like
// notifying our internalModel that we've "changed" and excessive thrash on
// setting up inverse relationships
this.canonicalMembers.add(internalModel);
this.members.add(internalModel);
this.inverseInternalModel = this.canonicalState = internalModel;
this.setupInverseRelationship(internalModel);
};
BelongsToRelationship.prototype.addCanonicalInternalModel = function addCanonicalInternalModel(internalModel) {
if (this.canonicalMembers.has(internalModel)) {
return;
}
if (this.canonicalState) {
this.removeCanonicalInternalModel(this.canonicalState);
}
this.canonicalState = internalModel;
_Relationship.prototype.addCanonicalInternalModel.call(this, internalModel);
};
BelongsToRelationship.prototype.inverseDidDematerialize = function inverseDidDematerialize() {
this.notifyBelongsToChanged();
};
BelongsToRelationship.prototype.flushCanonical = function flushCanonical() {
//temporary fix to not remove newly created records if server returned null.
//TODO remove once we have proper diffing
if (this.inverseInternalModel && this.inverseInternalModel.isNew() && !this.canonicalState) {
return;
}
if (this.inverseInternalModel !== this.canonicalState) {
this.inverseInternalModel = this.canonicalState;
this.notifyBelongsToChanged();
}
_Relationship.prototype.flushCanonical.call(this);
};
BelongsToRelationship.prototype.addInternalModel = function addInternalModel(internalModel) {
if (this.members.has(internalModel)) {
return;
}
(0, _debug.assertPolymorphicType)(this.internalModel, this.relationshipMeta, internalModel);
if (this.inverseInternalModel) {
this.removeInternalModel(this.inverseInternalModel);
}
this.inverseInternalModel = internalModel;
_Relationship.prototype.addInternalModel.call(this, internalModel);
this.notifyBelongsToChanged();
};
BelongsToRelationship.prototype.setRecordPromise = function setRecordPromise(newPromise) {
var content = newPromise.get && newPromise.get('content');
(false && _ember.default.assert("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined));
this.setInternalModel(content ? content._internalModel : content);
};
BelongsToRelationship.prototype.removeInternalModelFromOwn = function removeInternalModelFromOwn(internalModel) {
if (!this.members.has(internalModel)) {
return;
}
this.inverseInternalModel = null;
_Relationship.prototype.removeInternalModelFromOwn.call(this, internalModel);
this.notifyBelongsToChanged();
};
BelongsToRelationship.prototype.notifyBelongsToChanged = function notifyBelongsToChanged() {
this.internalModel.notifyBelongsToChanged(this.key);
};
BelongsToRelationship.prototype.removeCanonicalInternalModelFromOwn = function removeCanonicalInternalModelFromOwn(internalModel) {
if (!this.canonicalMembers.has(internalModel)) {
return;
}
this.canonicalState = null;
_Relationship.prototype.removeCanonicalInternalModelFromOwn.call(this, internalModel);
};
BelongsToRelationship.prototype.findRecord = function findRecord() {
if (this.inverseInternalModel) {
return this.store._findByInternalModel(this.inverseInternalModel);
} else {
return _ember.default.RSVP.Promise.resolve(null);
}
};
BelongsToRelationship.prototype.fetchLink = function fetchLink() {
var _this2 = this;
return this.store.findBelongsTo(this.internalModel, this.link, this.relationshipMeta).then(function (internalModel) {
if (internalModel) {
_this2.addInternalModel(internalModel);
}
return internalModel;
});
};
BelongsToRelationship.prototype.getRecord = function getRecord() {
var _this3 = this;
//TODO(Igor) flushCanonical here once our syncing is not stupid
if (this.isAsync) {
var promise = void 0;
if (this.link) {
if (this.hasLoaded) {
promise = this.findRecord();
} else {
promise = this.findLink().then(function () {
return _this3.findRecord();
});
}
} else {
promise = this.findRecord();
}
return _promiseProxies.PromiseObject.create({
promise: promise,
content: this.inverseInternalModel ? this.inverseInternalModel.getRecord() : null
});
} else {
if (this.inverseInternalModel === null) {
return null;
}
var toReturn = this.inverseInternalModel.getRecord();
(false && _ember.default.assert("You looked up the '" + this.key + "' relationship on a '" + this.internalModel.modelName + "' with id " + this.internalModel.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", toReturn === null || !toReturn.get('isEmpty')));
return toReturn;
}
};
BelongsToRelationship.prototype.reload = function reload() {
// TODO handle case when reload() is triggered multiple times
if (this.link) {
return this.fetchLink();
}
// reload record, if it is already loaded
if (this.inverseInternalModel && this.inverseInternalModel.hasRecord) {
return this.inverseInternalModel.getRecord().reload();
}
return this.findRecord();
};
BelongsToRelationship.prototype.updateData = function updateData(data, initial) {
(false && _ember.default.assert('Ember Data expected the data for the ' + this.key + ' relationship on a ' + this.internalModel.toString() + ' to be in a JSON API format and include an `id` and `type` property but it found ' + _ember.default.inspect(data) + '. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.', data === null || data.id !== undefined && data.type !== undefined));
var internalModel = this.store._pushResourceIdentifier(this, data);
if (initial) {
this.setInitialCanonicalInternalModel(internalModel);
} else {
this.setCanonicalInternalModel(internalModel);
}
};
return BelongsToRelationship;
}(_relationship.default);
exports.default = BelongsToRelationship;
});
define("ember-data/-private/system/relationships/state/create", ["exports", "ember", "ember-data/-private/system/relationships/state/has-many", "ember-data/-private/system/relationships/state/belongs-to"], function (exports, _ember, _hasMany, _belongsTo) {
"use strict";
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _get = _ember.default.get;
function shouldFindInverse(relationshipMeta) {
var options = relationshipMeta.options;
return !(options && options.inverse === null);
}
function createRelationshipFor(internalModel, relationshipMeta, store) {
var inverseKey = void 0;
var inverse = null;
if (shouldFindInverse(relationshipMeta)) {
inverse = internalModel.type.inverseFor(relationshipMeta.key, store);
} else if (false) {
internalModel.type.typeForRelationship(relationshipMeta.key, store);
}
if (inverse) {
inverseKey = inverse.name;
}
if (relationshipMeta.kind === 'hasMany') {
return new _hasMany.default(store, internalModel, inverseKey, relationshipMeta);
} else {
return new _belongsTo.default(store, internalModel, inverseKey, relationshipMeta);
}
}
var Relationships = function () {
function Relationships(internalModel) {
_classCallCheck(this, Relationships);
this.internalModel = internalModel;
this.initializedRelationships = Object.create(null);
}
// TODO @runspired deprecate this as it was never truly a record instance
Relationships.prototype.has = function has(key) {
return !!this.initializedRelationships[key];
};
Relationships.prototype.get = function get(key) {
var relationships = this.initializedRelationships;
var relationship = relationships[key];
var internalModel = this.internalModel;
if (!relationship) {
var relationshipsByName = _get(internalModel.type, 'relationshipsByName');
var rel = relationshipsByName.get(key);
if (!rel) {
return undefined;
}
var relationshipPayload = internalModel.store._relationshipsPayloads.get(internalModel.modelName, internalModel.id, key);
relationship = relationships[key] = createRelationshipFor(internalModel, rel, internalModel.store);
if (relationshipPayload) {
relationship.push(relationshipPayload, true);
}
}
return relationship;
};
_createClass(Relationships, [{
key: "record",
get: function () {
return this.internalModel;
}
}]);
return Relationships;
}();
exports.default = Relationships;
});
define('ember-data/-private/system/relationships/state/has-many', ['exports', 'ember-data/-debug', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/relationships/state/relationship', 'ember-data/-private/system/ordered-set', 'ember-data/-private/system/many-array'], function (exports, _debug, _promiseProxies, _relationship, _orderedSet, _manyArray) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
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 ManyRelationship = function (_Relationship) {
_inherits(ManyRelationship, _Relationship);
function ManyRelationship(store, internalModel, inverseKey, relationshipMeta) {
_classCallCheck(this, ManyRelationship);
var _this = _possibleConstructorReturn(this, _Relationship.call(this, store, internalModel, inverseKey, relationshipMeta));
_this.belongsToType = relationshipMeta.type;
_this.canonicalState = [];
_this.isPolymorphic = relationshipMeta.options.polymorphic;
_this._manyArray = null;
_this.__loadingPromise = null;
return _this;
}
ManyRelationship.prototype._updateLoadingPromise = function _updateLoadingPromise(promise, content) {
if (this.__loadingPromise) {
if (content) {
this.__loadingPromise.set('content', content);
}
this.__loadingPromise.set('promise', promise);
} else {
this.__loadingPromise = new _promiseProxies.PromiseManyArray({
promise: promise,
content: content
});
}
return this.__loadingPromise;
};
ManyRelationship.prototype.removeInverseRelationships = function removeInverseRelationships() {
_Relationship.prototype.removeInverseRelationships.call(this);
if (this._manyArray) {
this._manyArray.destroy();
this._manyArray = null;
}
if (this._loadingPromise) {
this._loadingPromise.destroy();
}
};
ManyRelationship.prototype.updateMeta = function updateMeta(meta) {
_Relationship.prototype.updateMeta.call(this, meta);
if (this._manyArray) {
this._manyArray.set('meta', meta);
}
};
ManyRelationship.prototype.addCanonicalInternalModel = function addCanonicalInternalModel(internalModel, idx) {
if (this.canonicalMembers.has(internalModel)) {
return;
}
if (idx !== undefined) {
this.canonicalState.splice(idx, 0, internalModel);
} else {
this.canonicalState.push(internalModel);
}
_Relationship.prototype.addCanonicalInternalModel.call(this, internalModel, idx);
};
ManyRelationship.prototype.inverseDidDematerialize = function inverseDidDematerialize() {
if (this._manyArray) {
this._manyArray.destroy();
this._manyArray = null;
}
this.notifyHasManyChanged();
};
ManyRelationship.prototype.addInternalModel = function addInternalModel(internalModel, idx) {
if (this.members.has(internalModel)) {
return;
}
(0, _debug.assertPolymorphicType)(this.internalModel, this.relationshipMeta, internalModel);
_Relationship.prototype.addInternalModel.call(this, internalModel, idx);
// make lazy later
this.manyArray._addInternalModels([internalModel], idx);
};
ManyRelationship.prototype.removeCanonicalInternalModelFromOwn = function removeCanonicalInternalModelFromOwn(internalModel, idx) {
var i = idx;
if (!this.canonicalMembers.has(internalModel)) {
return;
}
if (i === undefined) {
i = this.canonicalState.indexOf(internalModel);
}
if (i > -1) {
this.canonicalState.splice(i, 1);
}
_Relationship.prototype.removeCanonicalInternalModelFromOwn.call(this, internalModel, idx);
};
ManyRelationship.prototype.flushCanonical = function flushCanonical() {
if (this._manyArray) {
this._manyArray.flushCanonical();
}
_Relationship.prototype.flushCanonical.call(this);
};
ManyRelationship.prototype.removeInternalModelFromOwn = function removeInternalModelFromOwn(internalModel, idx) {
if (!this.members.has(internalModel)) {
return;
}
_Relationship.prototype.removeInternalModelFromOwn.call(this, internalModel, idx);
var manyArray = this.manyArray;
if (idx !== undefined) {
//TODO(Igor) not used currently, fix
manyArray.currentState.removeAt(idx);
} else {
manyArray._removeInternalModels([internalModel]);
}
};
ManyRelationship.prototype.notifyRecordRelationshipAdded = function notifyRecordRelationshipAdded(internalModel, idx) {
this.internalModel.notifyHasManyAdded(this.key, internalModel, idx);
};
ManyRelationship.prototype.reload = function reload() {
var manyArray = this.manyArray;
var manyArrayLoadedState = manyArray.get('isLoaded');
if (this._loadingPromise) {
if (this._loadingPromise.get('isPending')) {
return this._loadingPromise;
}
if (this._loadingPromise.get('isRejected')) {
manyArray.set('isLoaded', manyArrayLoadedState);
}
}
var promise = void 0;
if (this.link) {
promise = this.fetchLink();
} else {
promise = this.store._scheduleFetchMany(manyArray.currentState).then(function () {
return manyArray;
});
}
this._updateLoadingPromise(promise);
return this._loadingPromise;
};
ManyRelationship.prototype.computeChanges = function computeChanges() {
var internalModels = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var members = this.canonicalMembers;
var internalModelsToRemove = [];
var internalModelSet = setForArray(internalModels);
members.forEach(function (member) {
if (internalModelSet.has(member)) {
return;
}
internalModelsToRemove.push(member);
});
this.removeCanonicalInternalModels(internalModelsToRemove);
for (var i = 0, l = internalModels.length; i < l; i++) {
var internalModel = internalModels[i];
this.removeCanonicalInternalModel(internalModel);
this.addCanonicalInternalModel(internalModel, i);
}
};
ManyRelationship.prototype.setInitialInternalModels = function setInitialInternalModels(internalModels) {
var _this2 = this;
if (!internalModels) {
return;
}
var args = [0, this.canonicalState.length].concat(internalModels);
this.canonicalState.splice.apply(this.canonicalState, args);
internalModels.forEach(function (internalModel) {
_this2.canonicalMembers.add(internalModel);
_this2.members.add(internalModel);
_this2.setupInverseRelationship(internalModel);
});
};
ManyRelationship.prototype.fetchLink = function fetchLink() {
var _this3 = this;
return this.store.findHasMany(this.internalModel, this.link, this.relationshipMeta).then(function (records) {
if (records.hasOwnProperty('meta')) {
_this3.updateMeta(records.meta);
}
_this3.store._backburner.join(function () {
_this3.updateInternalModelsFromAdapter(records);
_this3.manyArray.set('isLoaded', true);
});
return _this3.manyArray;
});
};
ManyRelationship.prototype.findRecords = function findRecords() {
var manyArray = this.manyArray;
var internalModels = manyArray.currentState;
//TODO CLEANUP
return this.store.findMany(internalModels).then(function () {
if (!manyArray.get('isDestroyed')) {
//Goes away after the manyArray refactor
manyArray.set('isLoaded', true);
}
return manyArray;
});
};
ManyRelationship.prototype.notifyHasManyChanged = function notifyHasManyChanged() {
this.internalModel.notifyHasManyAdded(this.key);
};
ManyRelationship.prototype.getRecords = function getRecords() {
var _this4 = this;
//TODO(Igor) sync server here, once our syncing is not stupid
var manyArray = this.manyArray;
if (this.isAsync) {
var promise = void 0;
if (this.link) {
if (this.hasLoaded) {
promise = this.findRecords();
} else {
promise = this.findLink().then(function () {
return _this4.findRecords();
});
}
} else {
promise = this.findRecords();
}
return this._updateLoadingPromise(promise, manyArray);
} else {
(false && Ember.assert('You looked up the \'' + this.key + '\' relationship on a \'' + this.internalModel.type.modelName + '\' with id ' + this.internalModel.id + ' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (\'DS.hasMany({ async: true })\')', manyArray.isEvery('isEmpty', false)));
//TODO(Igor) WTF DO I DO HERE?
// TODO @runspired equal WTFs to Igor
if (!manyArray.get('isDestroyed')) {
manyArray.set('isLoaded', true);
}
return manyArray;
}
};
ManyRelationship.prototype.updateData = function updateData(data, initial) {
var internalModels = this.store._pushResourceIdentifiers(this, data);
if (initial) {
this.setInitialInternalModels(internalModels);
} else {
this.updateInternalModelsFromAdapter(internalModels);
}
};
_createClass(ManyRelationship, [{
key: '_loadingPromise',
get: function () {
return this.__loadingPromise;
}
}, {
key: 'manyArray',
get: function () {
if (!this._manyArray) {
this._manyArray = _manyArray.default.create({
canonicalState: this.canonicalState,
store: this.store,
relationship: this,
type: this.store.modelFor(this.belongsToType),
record: this.internalModel,
meta: this.meta,
isPolymorphic: this.isPolymorphic
});
}
return this._manyArray;
}
}]);
return ManyRelationship;
}(_relationship.default);
exports.default = ManyRelationship;
function setForArray(array) {
var set = new _orderedSet.default();
if (array) {
for (var i = 0, l = array.length; i < l; i++) {
set.add(array[i]);
}
}
return set;
}
});
define('ember-data/-private/system/relationships/state/relationship', ['exports', 'ember-data/-private/system/ordered-set', 'ember-data/-private/system/normalize-link'], function (exports, _orderedSet, _normalizeLink2) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var Relationship = function () {
function Relationship(store, internalModel, inverseKey, relationshipMeta) {
_classCallCheck(this, Relationship);
var async = relationshipMeta.options.async;
var polymorphic = relationshipMeta.options.polymorphic;
this.members = new _orderedSet.default();
this.canonicalMembers = new _orderedSet.default();
this.store = store;
this.key = relationshipMeta.key;
this.inverseKey = inverseKey;
this.internalModel = internalModel;
this.isAsync = typeof async === 'undefined' ? true : async;
this.isPolymorphic = typeof polymorphic === 'undefined' ? true : polymorphic;
this.relationshipMeta = relationshipMeta;
//This probably breaks for polymorphic relationship in complex scenarios, due to
//multiple possible modelNames
this.inverseKeyForImplicit = this.internalModel.modelName + this.key;
this.linkPromise = null;
this.meta = null;
this.hasData = false;
this.hasLoaded = false;
}
Relationship.prototype.removeInverseRelationships = function removeInverseRelationships() {
var _this = this;
if (!this.inverseKey) {
return;
}
var allMembers =
// we actually want a union of members and canonicalMembers
// they should be disjoint but currently are not due to a bug
this.members.toArray().concat(this.canonicalMembers.toArray());
allMembers.forEach(function (inverseInternalModel) {
var relationship = inverseInternalModel._relationships.get(_this.inverseKey);
relationship.inverseDidDematerialize();
});
};
Relationship.prototype.inverseDidDematerialize = function inverseDidDematerialize() {};
Relationship.prototype.updateMeta = function updateMeta(meta) {
this.meta = meta;
};
Relationship.prototype.clear = function clear() {
var members = this.members.list;
while (members.length > 0) {
var member = members[0];
this.removeInternalModel(member);
}
var canonicalMembers = this.canonicalMembers.list;
while (canonicalMembers.length > 0) {
var _member = canonicalMembers[0];
this.removeCanonicalInternalModel(_member);
}
};
Relationship.prototype.removeInternalModels = function removeInternalModels(internalModels) {
var _this2 = this;
internalModels.forEach(function (internalModel) {
return _this2.removeInternalModel(internalModel);
});
};
Relationship.prototype.addInternalModels = function addInternalModels(internalModels, idx) {
var _this3 = this;
internalModels.forEach(function (internalModel) {
_this3.addInternalModel(internalModel, idx);
if (idx !== undefined) {
idx++;
}
});
};
Relationship.prototype.addCanonicalInternalModels = function addCanonicalInternalModels(internalModels, idx) {
for (var i = 0; i < internalModels.length; i++) {
if (idx !== undefined) {
this.addCanonicalInternalModel(internalModels[i], i + idx);
} else {
this.addCanonicalInternalModel(internalModels[i]);
}
}
};
Relationship.prototype.addCanonicalInternalModel = function addCanonicalInternalModel(internalModel, idx) {
if (!this.canonicalMembers.has(internalModel)) {
this.canonicalMembers.add(internalModel);
this.setupInverseRelationship(internalModel);
}
this.flushCanonicalLater();
this.setHasData(true);
};
Relationship.prototype.setupInverseRelationship = function setupInverseRelationship(internalModel) {
if (this.inverseKey) {
var relationships = internalModel._relationships;
var relationshipExisted = relationships.has(this.inverseKey);
var relationship = relationships.get(this.inverseKey);
if (relationshipExisted || this.isPolymorphic) {
// if we have only just initialized the inverse relationship, then it
// already has this.internalModel in its canonicalMembers, so skip the
// unnecessary work. The exception to this is polymorphic
// relationships whose members are determined by their inverse, as those
// relationships cannot efficiently find their inverse payloads.
relationship.addCanonicalInternalModel(this.internalModel);
}
} else {
var _relationships = internalModel._implicitRelationships;
var _relationship = _relationships[this.inverseKeyForImplicit];
if (!_relationship) {
_relationship = _relationships[this.inverseKeyForImplicit] = new Relationship(this.store, internalModel, this.key, { options: {} });
}
_relationship.addCanonicalInternalModel(this.internalModel);
}
};
Relationship.prototype.removeCanonicalInternalModels = function removeCanonicalInternalModels(internalModels, idx) {
for (var i = 0; i < internalModels.length; i++) {
if (idx !== undefined) {
this.removeCanonicalInternalModel(internalModels[i], i + idx);
} else {
this.removeCanonicalInternalModel(internalModels[i]);
}
}
};
Relationship.prototype.removeCanonicalInternalModel = function removeCanonicalInternalModel(internalModel, idx) {
if (this.canonicalMembers.has(internalModel)) {
this.removeCanonicalInternalModelFromOwn(internalModel);
if (this.inverseKey) {
this.removeCanonicalInternalModelFromInverse(internalModel);
} else {
if (internalModel._implicitRelationships[this.inverseKeyForImplicit]) {
internalModel._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalInternalModel(this.internalModel);
}
}
}
this.flushCanonicalLater();
};
Relationship.prototype.addInternalModel = function addInternalModel(internalModel, idx) {
if (!this.members.has(internalModel)) {
this.members.addWithIndex(internalModel, idx);
this.notifyRecordRelationshipAdded(internalModel, idx);
if (this.inverseKey) {
internalModel._relationships.get(this.inverseKey).addInternalModel(this.internalModel);
} else {
if (!internalModel._implicitRelationships[this.inverseKeyForImplicit]) {
internalModel._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, internalModel, this.key, { options: {} });
}
internalModel._implicitRelationships[this.inverseKeyForImplicit].addInternalModel(this.internalModel);
}
this.internalModel.updateRecordArrays();
}
this.setHasData(true);
};
Relationship.prototype.removeInternalModel = function removeInternalModel(internalModel) {
if (this.members.has(internalModel)) {
this.removeInternalModelFromOwn(internalModel);
if (this.inverseKey) {
this.removeInternalModelFromInverse(internalModel);
} else {
if (internalModel._implicitRelationships[this.inverseKeyForImplicit]) {
internalModel._implicitRelationships[this.inverseKeyForImplicit].removeInternalModel(this.internalModel);
}
}
}
};
Relationship.prototype.removeInternalModelFromInverse = function removeInternalModelFromInverse(internalModel) {
var inverseRelationship = internalModel._relationships.get(this.inverseKey);
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeInternalModelFromOwn(this.internalModel);
}
};
Relationship.prototype.removeInternalModelFromOwn = function removeInternalModelFromOwn(internalModel) {
this.members.delete(internalModel);
this.notifyRecordRelationshipRemoved(internalModel);
this.internalModel.updateRecordArrays();
};
Relationship.prototype.removeCanonicalInternalModelFromInverse = function removeCanonicalInternalModelFromInverse(internalModel) {
var inverseRelationship = internalModel._relationships.get(this.inverseKey);
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeCanonicalInternalModelFromOwn(this.internalModel);
}
};
Relationship.prototype.removeCanonicalInternalModelFromOwn = function removeCanonicalInternalModelFromOwn(internalModel) {
this.canonicalMembers.delete(internalModel);
this.flushCanonicalLater();
};
Relationship.prototype.flushCanonical = function flushCanonical() {
var list = this.members.list;
this.willSync = false;
//a hack for not removing new internalModels
//TODO remove once we have proper diffing
var newInternalModels = [];
for (var i = 0; i < list.length; i++) {
if (list[i].isNew()) {
newInternalModels.push(list[i]);
}
}
//TODO(Igor) make this less abysmally slow
this.members = this.canonicalMembers.copy();
for (var _i = 0; _i < newInternalModels.length; _i++) {
this.members.add(newInternalModels[_i]);
}
};
Relationship.prototype.flushCanonicalLater = function flushCanonicalLater() {
if (this.willSync) {
return;
}
this.willSync = true;
this.store._updateRelationshipState(this);
};
Relationship.prototype.updateLink = function updateLink(link) {
(false && Ember.warn('You pushed a record of type \'' + this.internalModel.modelName + '\' with a relationship \'' + this.key + '\' configured as \'async: false\'. You\'ve included a link but no primary data, this may be an error in your payload.', this.isAsync || this.hasData, {
id: 'ds.store.push-link-for-sync-relationship'
}));
(false && Ember.assert('You have pushed a record of type \'' + this.internalModel.modelName + '\' with \'' + this.key + '\' as a link, but the value of that link is not a string.', typeof link === 'string' || link === null));
this.link = link;
this.linkPromise = null;
this.internalModel.notifyPropertyChange(this.key);
};
Relationship.prototype.findLink = function findLink() {
if (this.linkPromise) {
return this.linkPromise;
} else {
var promise = this.fetchLink();
this.linkPromise = promise;
return promise.then(function (result) {
return result;
});
}
};
Relationship.prototype.updateInternalModelsFromAdapter = function updateInternalModelsFromAdapter(internalModels) {
//TODO(Igor) move this to a proper place
//TODO Once we have adapter support, we need to handle updated and canonical changes
this.computeChanges(internalModels);
};
Relationship.prototype.notifyRecordRelationshipAdded = function notifyRecordRelationshipAdded() {};
Relationship.prototype.notifyRecordRelationshipRemoved = function notifyRecordRelationshipRemoved() {};
Relationship.prototype.setHasData = function setHasData(value) {
this.hasData = value;
};
Relationship.prototype.setHasLoaded = function setHasLoaded(value) {
this.hasLoaded = value;
};
Relationship.prototype.push = function push(payload, initial) {
var hasData = false;
var hasLink = false;
if (payload.meta) {
this.updateMeta(payload.meta);
}
if (payload.data !== undefined) {
hasData = true;
this.updateData(payload.data, initial);
}
if (payload.links && payload.links.related) {
var relatedLink = (0, _normalizeLink2.default)(payload.links.related);
if (relatedLink && relatedLink.href && relatedLink.href !== this.link) {
hasLink = true;
this.updateLink(relatedLink.href, initial);
}
}
/*
Data being pushed into the relationship might contain only data or links,
or a combination of both.
If we got data we want to set both hasData and hasLoaded to true since
this would indicate that we should prefer the local state instead of
trying to fetch the link or call findRecord().
If we have no data but a link is present we want to set hasLoaded to false
without modifying the hasData flag. This will ensure we fetch the updated
link next time the relationship is accessed.
*/
if (hasData) {
this.setHasData(true);
this.setHasLoaded(true);
} else if (hasLink) {
this.setHasLoaded(false);
}
};
Relationship.prototype.updateData = function updateData() {};
_createClass(Relationship, [{
key: 'parentType',
get: function () {
return this.internalModel.modelName;
}
}]);
return Relationship;
}();
exports.default = Relationship;
});
define('ember-data/-private/system/snapshot-record-array', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _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 SnapshotRecordArray = function () {
function SnapshotRecordArray(recordArray, meta) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck(this, SnapshotRecordArray);
/**
An array of snapshots
@private
@property _snapshots
@type {Array}
*/
this._snapshots = null;
/**
An array of records
@private
@property _recordArray
@type {Array}
*/
this._recordArray = recordArray;
/**
Number of records in the array
Example
```app/adapters/post.js
import DS from 'ember-data'
export default DS.JSONAPIAdapter.extend({
shouldReloadAll(store, snapshotRecordArray) {
return !snapshotRecordArray.length;
},
});
```
@property length
@type {Number}
*/
this.length = recordArray.get('length');
this._type = null;
/**
Meta objects for the record array.
Example
```app/adapters/post.js
import DS from 'ember-data'
export default DS.JSONAPIAdapter.extend({
shouldReloadAll(store, snapshotRecordArray) {
var lastRequestTime = snapshotRecordArray.meta.lastRequestTime;
var twentyMinutes = 20 * 60 * 1000;
return Date.now() > lastRequestTime + twentyMinutes;
},
});
```
@property meta
@type {Object}
*/
this.meta = meta;
/**
A hash of adapter options passed into the store method for this request.
Example
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
findAll(store, type, sinceToken, snapshotRecordArray) {
if (snapshotRecordArray.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
@property adapterOptions
@type {Object}
*/
this.adapterOptions = options.adapterOptions;
/**
The relationships to include for this request.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
findAll(store, type, snapshotRecordArray) {
var url = `/${type.modelName}?include=${encodeURIComponent(snapshotRecordArray.include)}`;
return fetch(url).then((response) => response.json())
}
});
@property include
@type {String|Array}
*/
this.include = options.include;
}
/**
The type of the underlying records for the snapshots in the array, as a DS.Model
@property type
@type {DS.Model}
*/
SnapshotRecordArray.prototype.snapshots = function snapshots() {
if (this._snapshots !== null) {
return this._snapshots;
}
this._snapshots = this._recordArray._takeSnapshot();
return this._snapshots;
};
_createClass(SnapshotRecordArray, [{
key: 'type',
get: function () {
return this._type || (this._type = this._recordArray.get('type'));
}
}]);
return SnapshotRecordArray;
}();
exports.default = SnapshotRecordArray;
});
define("ember-data/-private/system/snapshot", ["exports", "ember"], function (exports, _ember) {
"use strict";
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var get = _ember.default.get;
var Snapshot = function () {
function Snapshot(internalModel) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Snapshot);
this._attributes = Object.create(null);
this._belongsToRelationships = Object.create(null);
this._belongsToIds = Object.create(null);
this._hasManyRelationships = Object.create(null);
this._hasManyIds = Object.create(null);
this._internalModel = internalModel;
var record = internalModel.getRecord();
/**
The underlying record for this snapshot. Can be used to access methods and
properties defined on the record.
Example
```javascript
let json = snapshot.record.toJSON();
```
@property record
@type {DS.Model}
*/
this.record = record;
record.eachAttribute(function (keyName) {
return _this._attributes[keyName] = get(record, keyName);
});
/**
The id of the snapshot's underlying record
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postSnapshot.id; // => '1'
```
@property id
@type {String}
*/
this.id = internalModel.id;
/**
A hash of adapter options
@property adapterOptions
@type {Object}
*/
this.adapterOptions = options.adapterOptions;
this.include = options.include;
/**
The name of the type of the underlying record for this snapshot, as a string.
@property modelName
@type {String}
*/
this.modelName = internalModel.modelName;
this._changedAttributes = record.changedAttributes();
}
/**
The type of the underlying record for this snapshot, as a DS.Model.
@property type
@type {DS.Model}
*/
Snapshot.prototype.attr = function attr(keyName) {
if (keyName in this._attributes) {
return this._attributes[keyName];
}
throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no attribute named '" + keyName + "' defined.");
};
Snapshot.prototype.attributes = function attributes() {
return _ember.default.copy(this._attributes);
};
Snapshot.prototype.changedAttributes = function changedAttributes() {
var changedAttributes = Object.create(null);
var changedAttributeKeys = Object.keys(this._changedAttributes);
for (var i = 0, length = changedAttributeKeys.length; i < length; i++) {
var key = changedAttributeKeys[i];
changedAttributes[key] = _ember.default.copy(this._changedAttributes[key]);
}
return changedAttributes;
};
Snapshot.prototype.belongsTo = function belongsTo(keyName, options) {
var id = options && options.id;
var relationship = void 0,
inverseInternalModel = void 0,
hasData = void 0;
var result = void 0;
if (id && keyName in this._belongsToIds) {
return this._belongsToIds[keyName];
}
if (!id && keyName in this._belongsToRelationships) {
return this._belongsToRelationships[keyName];
}
relationship = this._internalModel._relationships.get(keyName);
if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) {
throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined.");
}
hasData = get(relationship, 'hasData');
inverseInternalModel = get(relationship, 'inverseInternalModel');
if (hasData) {
if (inverseInternalModel && !inverseInternalModel.isDeleted()) {
if (id) {
result = get(inverseInternalModel, 'id');
} else {
result = inverseInternalModel.createSnapshot();
}
} else {
result = null;
}
}
if (id) {
this._belongsToIds[keyName] = result;
} else {
this._belongsToRelationships[keyName] = result;
}
return result;
};
Snapshot.prototype.hasMany = function hasMany(keyName, options) {
var ids = options && options.ids;
var relationship = void 0,
members = void 0,
hasData = void 0;
var results = void 0;
if (ids && keyName in this._hasManyIds) {
return this._hasManyIds[keyName];
}
if (!ids && keyName in this._hasManyRelationships) {
return this._hasManyRelationships[keyName];
}
relationship = this._internalModel._relationships.get(keyName);
if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) {
throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined.");
}
hasData = get(relationship, 'hasData');
members = get(relationship, 'members');
if (hasData) {
results = [];
members.forEach(function (member) {
if (!member.isDeleted()) {
if (ids) {
results.push(member.id);
} else {
results.push(member.createSnapshot());
}
}
});
}
if (ids) {
this._hasManyIds[keyName] = results;
} else {
this._hasManyRelationships[keyName] = results;
}
return results;
};
Snapshot.prototype.eachAttribute = function eachAttribute(callback, binding) {
this.record.eachAttribute(callback, binding);
};
Snapshot.prototype.eachRelationship = function eachRelationship(callback, binding) {
this.record.eachRelationship(callback, binding);
};
Snapshot.prototype.serialize = function serialize(options) {
return this.record.store.serializerFor(this.modelName).serialize(this, options);
};
_createClass(Snapshot, [{
key: "type",
get: function () {
// TODO @runspired we should deprecate this in favor of modelClass but only once
// we've cleaned up the internals enough that a public change to follow suite is
// uncontroversial.
return this._internalModel.modelClass;
}
}]);
return Snapshot;
}();
exports.default = Snapshot;
});
define('ember-data/-private/system/store', ['exports', 'ember', 'ember-data/-private/adapters/errors', 'ember-data/-debug', 'ember-data/-private/system/model/model', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/system/identity-map', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers', 'ember-data/-private/system/relationships/relationship-payloads-manager', 'ember-data/-private/system/store/finders', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/features'], function (exports, _ember, _errors, _debug, _model, _normalizeModelName, _identityMap, _promiseProxies, _common, _serializerResponse, _serializers, _relationshipPayloadsManager, _finders, _utils, _coerceId, _recordArrayManager, _containerInstanceCache, _internalModel5, _features) {
'use strict';
exports.__esModule = true;
exports.Store = undefined;
/**
@module ember-data
*/
var badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number';
var A = _ember.default.A,
Backburner = _ember.default._Backburner,
computed = _ember.default.computed,
copy = _ember.default.copy,
ENV = _ember.default.ENV,
EmberError = _ember.default.Error,
get = _ember.default.get,
inspect = _ember.default.inspect,
isNone = _ember.default.isNone,
isPresent = _ember.default.isPresent,
MapWithDefault = _ember.default.MapWithDefault,
emberRun = _ember.default.run,
set = _ember.default.set,
RSVP = _ember.default.RSVP,
Service = _ember.default.Service,
typeOf = _ember.default.typeOf;
var Promise = RSVP.Promise;
//Get the materialized model from the internalModel/promise that returns
//an internal model and return it in a promiseObject. Useful for returning
//from find methods
function promiseRecord(internalModelPromise, label) {
var toReturn = internalModelPromise.then(function (internalModel) {
return internalModel.getRecord();
});
return (0, _promiseProxies.promiseObject)(toReturn, label);
}
var Store = void 0;
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +internalModel+ means a record internalModel object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a DS.Model.
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```app/services/store.js
import DS from 'ember-data';
export default DS.Store.extend({
});
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `findRecord()` method:
```javascript
store.findRecord('person', 123).then(function (person) {
});
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
});
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
### Store createRecord() vs. push() vs. pushPayload()
The store provides multiple ways to create new record objects. They have
some subtle differences in their use which are detailed below:
[createRecord](#method_createRecord) is used for creating new
records on the client side. This will return a new record in the
`created.uncommitted` state. In order to persist this record to the
backend you will need to call `record.save()`.
[push](#method_push) is used to notify Ember Data's store of new or
updated records that exist in the backend. This will return a record
in the `loaded.saved` state. The primary use-case for `store#push` is
to notify Ember Data about record updates (full or partial) that happen
outside of the normal adapter methods (for example
[SSE](http://dev.w3.org/html5/eventsource/) or [Web
Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)).
[pushPayload](#method_pushPayload) is a convenience wrapper for
`store#push` that will deserialize payloads if the
Serializer implements a `pushPayload` method.
Note: When creating a new record using any of the above methods
Ember Data will update `DS.RecordArray`s such as those returned by
`store#peekAll()`, `store#findAll()` or `store#filter()`. This means any
data bindings or computed properties that depend on the RecordArray
will automatically be synced to include the new or updated record
values.
@class Store
@namespace DS
@extends Ember.Service
*/
exports.Store = Store = Service.extend({
/**
@method init
@private
*/
init: function () {
this._super.apply(this, arguments);
this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']);
// internal bookkeeping; not observable
this.recordArrayManager = new _recordArrayManager.default({ store: this });
this._identityMap = new _identityMap.default();
this._pendingSave = [];
this._instanceCache = new _containerInstanceCache.default((0, _utils.getOwner)(this), this);
this._modelFactoryCache = Object.create(null);
this._relationshipsPayloads = new _relationshipPayloadsManager.default(this);
/*
Ember Data uses several specialized micro-queues for organizing
and coalescing similar async work.
These queues are currently controlled by a flush scheduled into
ember-data's custom backburner instance.
*/
// used for coalescing record save requests
this._pendingSave = [];
// used for coalescing relationship updates
this._updatedRelationships = [];
// used for coalescing relationship setup needs
this._pushedInternalModels = [];
// used for coalescing internal model updates
this._updatedInternalModels = [];
// used to keep track of all the find requests that need to be coalesced
this._pendingFetch = MapWithDefault.create({
defaultValue: function () {
return [];
}
});
this._instanceCache = new _containerInstanceCache.default((0, _utils.getOwner)(this), this);
},
/**
The default adapter to use to communicate to a backend server or
other persistence layer. This will be overridden by an application
adapter if present.
If you want to specify `app/adapters/custom.js` as a string, do:
```js
import DS from 'ember-data';
export default DS.Store.extend({
adapter: 'custom',
});
```
@property adapter
@default '-json-api'
@type {String}
*/
adapter: '-json-api',
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@deprecated
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function (record, options) {
if (true) {
(false && !(false) && _ember.default.deprecate('Use of store.serialize is deprecated, use record.serialize instead.', false, {
id: 'ds.store.serialize',
until: '3.0'
}));
}
var snapshot = record._internalModel.createSnapshot();
return snapshot.serialize(options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@return DS.Adapter
*/
defaultAdapter: computed('adapter', function () {
var adapter = get(this, 'adapter');
(false && _ember.default.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', typeof adapter === 'string'));
return this.adapterFor(adapter);
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of a `Post`:
```js
store.createRecord('post', {
title: 'Rails is omakase'
});
```
To create a new instance of a `Post` that has a relationship with a `User` record:
```js
let user = this.store.peekRecord('user', 1);
store.createRecord('post', {
title: 'Rails is omakase',
user: user
});
```
@method createRecord
@param {String} modelName
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {DS.Model} record
*/
createRecord: function (modelName, inputProperties) {
(false && _ember.default.assert('You need to pass a model name to the store\'s createRecord method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
var properties = copy(inputProperties) || Object.create(null);
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (isNone(properties.id)) {
properties.id = this._generateId(normalizedModelName, properties);
}
// Coerce ID to a string
properties.id = (0, _coerceId.default)(properties.id);
var internalModel = this._buildInternalModel(normalizedModelName, properties.id);
internalModel.loadedData();
var record = internalModel.getRecord(properties);
// TODO @runspired this should also be coalesced into some form of internalModel.setState()
internalModel.eachRelationship(function (key, descriptor) {
internalModel._relationships.get(key).setHasData(true);
});
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} modelName
@param {Object} properties from the new record
@return {String} if the adapter can generate one, an ID
*/
_generateId: function (modelName, properties) {
var adapter = this.adapterFor(modelName);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this, modelName, properties);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
let post = store.createRecord('post', {
title: 'Rails is omakase'
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function (record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store.
This will cause the record to be destroyed and freed up for garbage collection.
Example
```javascript
store.findRecord('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function (record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
@method find
@param {String} modelName
@param {String|Integer} id
@param {Object} options
@return {Promise} promise
@private
*/
find: function (modelName, id, options) {
// The default `model` hook in Ember.Route calls `find(modelName, id)`,
// that's why we have to keep this method around even though `findRecord` is
// the public way to get a record by modelName and id.
(false && _ember.default.assert('Using store.find(type) has been removed. Use store.findAll(modelName) to retrieve all records for a given type.', arguments.length !== 1));
(false && _ember.default.assert('Calling store.find(modelName, id, { preload: preload }) is no longer supported. Use store.findRecord(modelName, id, { preload: preload }) instead.', !options));
(false && _ember.default.assert('You need to pass the model name and id to the store\'s find method', arguments.length === 2));
(false && _ember.default.assert('You cannot pass \'' + id + '\' as id to the store\'s find method', typeof id === 'string' || typeof id === 'number'));
(false && _ember.default.assert('Calling store.find() with a query object is no longer supported. Use store.query() instead.', typeof id !== 'object'));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
return this.findRecord(normalizedModelName, id);
},
/**
This method returns a record for a given type and id combination.
The `findRecord` method will always resolve its promise with the same
object for a given type and `id`.
The `findRecord` method will always return a **promise** that will be
resolved with the record.
Example
```app/routes/post.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id);
}
});
```
If the record is not yet available, the store will ask the adapter's `find`
method to find the necessary data. If the record is already present in the
store, it depends on the reload behavior _when_ the returned promise
resolves.
### Preloading
You can optionally `preload` specific attributes and relationships that you know of
by passing them via the passed `options`.
For example, if your Ember route looks like `/posts/1/comments/2` and your API route
for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
without fetching the post you can pass in the post to the `findRecord` call:
```javascript
store.findRecord('comment', 2, { preload: { post: 1 } });
```
If you have access to the post model you can also pass the model itself:
```javascript
store.findRecord('post', 1).then(function (myPostModel) {
store.findRecord('comment', 2, { post: myPostModel });
});
```
### Reloading
The reload behavior is configured either via the passed `options` hash or
the result of the adapter's `shouldReloadRecord`.
If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates
to `true`, then the returned promise resolves once the adapter returns
data, regardless if the requested record is already in the store:
```js
store.push({
data: {
id: 1,
type: 'post',
revision: 1
}
});
// adapter#findRecord resolves with
// [
// {
// id: 1,
// type: 'post',
// revision: 2
// }
// ]
store.findRecord('post', 1, { reload: true }).then(function(post) {
post.get('revision'); // 2
});
```
If no reload is indicated via the abovementioned ways, then the promise
immediately resolves with the cached version in the store.
### Background Reloading
Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`,
then a background reload is started, which updates the records' data, once
it is available:
```js
// app/adapters/post.js
import ApplicationAdapter from "./application";
export default ApplicationAdapter.extend({
shouldReloadRecord(store, snapshot) {
return false;
},
shouldBackgroundReloadRecord(store, snapshot) {
return true;
}
});
// ...
store.push({
data: {
id: 1,
type: 'post',
revision: 1
}
});
let blogPost = store.findRecord('post', 1).then(function(post) {
post.get('revision'); // 1
});
// later, once adapter#findRecord resolved with
// [
// {
// id: 1,
// type: 'post',
// revision: 2
// }
// ]
blogPost.get('revision'); // 2
```
If you would like to force or prevent background reloading, you can set a
boolean value for `backgroundReload` in the options object for
`findRecord`.
```app/routes/post/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, { backgroundReload: false });
}
});
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to you adapter via the snapshot
```app/routes/post/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, {
adapterOptions: { subscribe: false }
});
}
});
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
findRecord(store, type, id, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
See [peekRecord](#method_peekRecord) to get the cached version of a record.
### Retrieving Related Model Records
If you use an adapter such as Ember's default
[`JSONAPIAdapter`](http://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html)
that supports the [JSON API specification](http://jsonapi.org/) and if your server
endpoint supports the use of an
['include' query parameter](http://jsonapi.org/format/#fetching-includes),
you can use `findRecord()` to automatically retrieve additional records related to
the one you request by supplying an `include` parameter in the `options` object.
For example, given a `post` model that has a `hasMany` relationship with a `comment`
model, when we retrieve a specific post we can have the server also return that post's
comments in the same request:
```app/routes/post.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, { include: 'comments' });
}
});
```
In this case, the post's comments would then be available in your template as
`model.comments`.
Multiple relationships can be requested using an `include` parameter consisting of a
comma-separated list (without white-space) while nested relationships can be specified
using a dot-separated sequence of relationship names. So to request both the post's
comments and the authors of those comments the request would look like this:
```app/routes/post.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findRecord('post', params.post_id, { include: 'comments,comments.author' });
}
});
```
@since 1.13.0
@method findRecord
@param {String} modelName
@param {(String|Integer)} id
@param {Object} options
@return {Promise} promise
*/
findRecord: function (modelName, id, options) {
(false && _ember.default.assert('You need to pass a model name to the store\'s findRecord method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
(false && _ember.default.assert(badIdFormatAssertion, typeof id === 'string' && id.length > 0 || typeof id === 'number' && !isNaN(id)));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
var internalModel = this._internalModelForId(normalizedModelName, id);
options = options || {};
if (!this.hasRecordForId(normalizedModelName, id)) {
return this._findByInternalModel(internalModel, options);
}
var fetchedInternalModel = this._findRecord(internalModel, options);
return promiseRecord(fetchedInternalModel, 'DS: Store#findRecord ' + normalizedModelName + ' with id: ' + id);
},
_findRecord: function (internalModel, options) {
// Refetch if the reload option is passed
if (options.reload) {
return this._scheduleFetch(internalModel, options);
}
var snapshot = internalModel.createSnapshot(options);
var adapter = this.adapterFor(internalModel.modelName);
// Refetch the record if the adapter thinks the record is stale
if (adapter.shouldReloadRecord(this, snapshot)) {
return this._scheduleFetch(internalModel, options);
}
if (options.backgroundReload === false) {
return Promise.resolve(internalModel);
}
// Trigger the background refetch if backgroundReload option is passed
if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) {
this._scheduleFetch(internalModel, options);
}
// Return the cached record
return Promise.resolve(internalModel);
},
_findByInternalModel: function (internalModel) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (options.preload) {
internalModel.preloadData(options.preload);
}
var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options);
return promiseRecord(fetchedInternalModel, 'DS: Store#findRecord ' + internalModel.modelName + ' with id: ' + internalModel.id);
},
_findEmptyInternalModel: function (internalModel, options) {
if (internalModel.isEmpty()) {
return this._scheduleFetch(internalModel, options);
}
//TODO double check about reloading
if (internalModel.isLoading()) {
return internalModel._loadingPromise;
}
return Promise.resolve(internalModel);
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} modelName
@param {Array} ids
@return {Promise} promise
*/
findByIds: function (modelName, ids) {
(false && _ember.default.assert('You need to pass a model name to the store\'s findByIds method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var promises = new Array(ids.length);
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
for (var i = 0; i < ids.length; i++) {
promises[i] = this.findRecord(normalizedModelName, ids[i]);
}
return (0, _promiseProxies.promiseArray)(RSVP.all(promises).then(A, null, 'DS: Store#findByIds of ' + normalizedModelName + ' complete'));
},
/**
This method is called by `findRecord` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method _fetchRecord
@private
@param {InternalModel} internalModel model
@return {Promise} promise
*/
_fetchRecord: function (internalModel, options) {
var modelName = internalModel.modelName;
var adapter = this.adapterFor(modelName);
(false && _ember.default.assert('You tried to find a record but you have no adapter (for ' + modelName + ')', adapter));
(false && _ember.default.assert('You tried to find a record but your adapter (for ' + modelName + ') does not implement \'findRecord\'', typeof adapter.findRecord === 'function'));
return (0, _finders._find)(adapter, this, internalModel.type, internalModel.id, internalModel, options);
},
_scheduleFetchMany: function (internalModels) {
var fetches = new Array(internalModels.length);
for (var i = 0; i < internalModels.length; i++) {
fetches[i] = this._scheduleFetch(internalModels[i]);
}
return Promise.all(fetches);
},
_scheduleFetch: function (internalModel, options) {
if (internalModel._loadingPromise) {
return internalModel._loadingPromise;
}
var id = internalModel.id,
modelName = internalModel.modelName;
var resolver = RSVP.defer('Fetching ' + modelName + '\' with id: ' + id);
var pendingFetchItem = {
internalModel: internalModel,
resolver: resolver,
options: options
};
var promise = resolver.promise;
internalModel.loadingData(promise);
if (this._pendingFetch.size === 0) {
emberRun.schedule('afterRender', this, this.flushAllPendingFetches);
}
this._pendingFetch.get(modelName).push(pendingFetchItem);
return promise;
},
flushAllPendingFetches: function () {
if (this.isDestroyed || this.isDestroying) {
return;
}
this._pendingFetch.forEach(this._flushPendingFetchForType, this);
this._pendingFetch.clear();
},
_flushPendingFetchForType: function (pendingFetchItems, modelName) {
var store = this;
var adapter = store.adapterFor(modelName);
var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
var totalItems = pendingFetchItems.length;
var internalModels = new Array(totalItems);
var seeking = Object.create(null);
for (var _i = 0; _i < totalItems; _i++) {
var pendingItem = pendingFetchItems[_i];
var _internalModel = pendingItem.internalModel;
internalModels[_i] = _internalModel;
seeking[_internalModel.id] = pendingItem;
}
function _fetchRecord(recordResolverPair) {
var recordFetch = store._fetchRecord(recordResolverPair.internalModel, recordResolverPair.options); // TODO adapter options
recordResolverPair.resolver.resolve(recordFetch);
}
function handleFoundRecords(foundInternalModels, expectedInternalModels) {
// resolve found records
var found = Object.create(null);
for (var _i2 = 0, _l = foundInternalModels.length; _i2 < _l; _i2++) {
var _internalModel2 = foundInternalModels[_i2];
var _pair = seeking[_internalModel2.id];
found[_internalModel2.id] = _internalModel2;
if (_pair) {
var resolver = _pair.resolver;
resolver.resolve(_internalModel2);
}
}
// reject missing records
var missingInternalModels = [];
for (var _i3 = 0, _l2 = expectedInternalModels.length; _i3 < _l2; _i3++) {
var _internalModel3 = expectedInternalModels[_i3];
if (!found[_internalModel3.id]) {
missingInternalModels.push(_internalModel3);
}
}
if (missingInternalModels.length) {
(false && _ember.default.warn('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + inspect(missingInternalModels.map(function (r) {
return r.id;
})), false, {
id: 'ds.store.missing-records-from-adapter'
}));
rejectInternalModels(missingInternalModels);
}
}
function rejectInternalModels(internalModels, error) {
for (var _i4 = 0, _l3 = internalModels.length; _i4 < _l3; _i4++) {
var _internalModel4 = internalModels[_i4];
var _pair2 = seeking[_internalModel4.id];
if (_pair2) {
_pair2.resolver.reject(error || new Error('Expected: \'' + _internalModel4 + '\' to be present in the adapter provided payload, but it was not found.'));
}
}
}
if (shouldCoalesce) {
// TODO: Improve records => snapshots => records => snapshots
//
// We want to provide records to all store methods and snapshots to all
// adapter methods. To make sure we're doing that we're providing an array
// of snapshots to adapter.groupRecordsForFindMany(), which in turn will
// return grouped snapshots instead of grouped records.
//
// But since the _findMany() finder is a store method we need to get the
// records from the grouped snapshots even though the _findMany() finder
// will once again convert the records to snapshots for adapter.findMany()
var snapshots = new Array(totalItems);
for (var _i5 = 0; _i5 < totalItems; _i5++) {
snapshots[_i5] = internalModels[_i5].createSnapshot();
}
var groups = adapter.groupRecordsForFindMany(this, snapshots);
for (var i = 0, l = groups.length; i < l; i++) {
var group = groups[i];
var totalInGroup = groups[i].length;
var ids = new Array(totalInGroup);
var groupedInternalModels = new Array(totalInGroup);
for (var j = 0; j < totalInGroup; j++) {
var internalModel = group[j]._internalModel;
groupedInternalModels[j] = internalModel;
ids[j] = internalModel.id;
}
if (totalInGroup > 1) {
(function (groupedInternalModels) {
(0, _finders._findMany)(adapter, store, modelName, ids, groupedInternalModels).then(function (foundInternalModels) {
handleFoundRecords(foundInternalModels, groupedInternalModels);
}).catch(function (error) {
rejectInternalModels(groupedInternalModels, error);
});
})(groupedInternalModels);
} else if (ids.length === 1) {
var pair = seeking[groupedInternalModels[0].id];
_fetchRecord(pair);
} else {
(false && _ember.default.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false));
}
}
} else {
for (var _i6 = 0; _i6 < totalItems; _i6++) {
_fetchRecord(pendingFetchItems[_i6]);
}
}
},
/**
Get the reference for the specified record.
Example
```javascript
let userRef = store.getReference('user', 1);
// check if the user is loaded
let isLoaded = userRef.value() !== null;
// get the record of the reference (null if not yet available)
let user = userRef.value();
// get the identifier of the reference
if (userRef.remoteType() === 'id') {
let id = userRef.id();
}
// load user (via store.find)
userRef.load().then(...)
// or trigger a reload
userRef.reload().then(...)
// provide data for reference
userRef.push({ id: 1, username: '@user' }).then(function(user) {
userRef.value() === user;
});
```
@method getReference
@param {String} modelName
@param {String|Integer} id
@since 2.5.0
@return {RecordReference}
*/
getReference: function (modelName, id) {
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
return this._internalModelForId(normalizedModelName, id).recordReference;
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store,
otherwise it will return `null`. A record is available if it has been fetched earlier, or
pushed manually into the store.
See [findRecord](#method_findRecord) if you would like to request this record from the backend.
_Note: This is a synchronous method and does not return a promise._
```js
let post = store.peekRecord('post', 1);
post.get('id'); // 1
```
@since 1.13.0
@method peekRecord
@param {String} modelName
@param {String|Integer} id
@return {DS.Model|null} record
*/
peekRecord: function (modelName, id) {
(false && _ember.default.assert('You need to pass a model name to the store\'s peekRecord method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
if (this.hasRecordForId(normalizedModelName, id)) {
return this._internalModelForId(normalizedModelName, id).getRecord();
} else {
return null;
}
},
/**
This method is called by the record's `reload` method.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} internalModel
@return {Promise} promise
*/
_reloadRecord: function (internalModel) {
var id = internalModel.id,
modelName = internalModel.modelName;
var adapter = this.adapterFor(modelName);
(false && _ember.default.assert('You cannot reload a record without an ID', id));
(false && _ember.default.assert('You tried to reload a record but you have no adapter (for ' + modelName + ')', adapter));
(false && _ember.default.assert('You tried to reload a record but your adapter does not implement \'findRecord\'', typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'));
return this._scheduleFetch(internalModel);
},
/**
This method returns true if a record for a given modelName and id is already
loaded in the store. Use this function to know beforehand if a findRecord()
will result in a request or that it will be a cache hit.
Example
```javascript
store.hasRecordForId('post', 1); // false
store.findRecord('post', 1).then(function() {
store.hasRecordForId('post', 1); // true
});
```
@method hasRecordForId
@param {String} modelName
@param {(String|Integer)} id
@return {Boolean}
*/
hasRecordForId: function (modelName, id) {
(false && _ember.default.assert('You need to pass a model name to the store\'s hasRecordForId method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
var trueId = (0, _coerceId.default)(id);
var internalModel = this._internalModelsFor(normalizedModelName).get(trueId);
return !!internalModel && internalModel.isLoaded();
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@private
@param {String} modelName
@param {(String|Integer)} id
@return {DS.Model} record
*/
recordForId: function (modelName, id) {
(false && _ember.default.assert('You need to pass a model name to the store\'s recordForId method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
return this._internalModelForId(modelName, id).getRecord();
},
_internalModelForId: function (modelName, id) {
var trueId = (0, _coerceId.default)(id);
var internalModel = this._internalModelsFor(modelName).get(trueId);
if (!internalModel) {
internalModel = this._buildInternalModel(modelName, trueId);
} else {
// if we already have an internalModel, we need to ensure any async teardown is cancelled
// since we want it again.
internalModel.cancelDestroy();
}
return internalModel;
},
_internalModelDidReceiveRelationshipData: function (modelName, id, relationshipData) {
this._relationshipsPayloads.push(modelName, id, relationshipData);
},
_internalModelDestroyed: function (internalModel) {
this._removeFromIdMap(internalModel);
this._relationshipsPayloads.unload(internalModel.modelName, internalModel.id);
},
/**
@method findMany
@private
@param {Array} internalModels
@return {Promise} promise
*/
findMany: function (internalModels) {
var finds = new Array(internalModels.length);
for (var i = 0; i < internalModels.length; i++) {
finds[i] = this._findEmptyInternalModel(internalModels[i]);
}
return Promise.all(finds);
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {InternalModel} internalModel
@param {any} link
@param {(Relationship)} relationship
@return {Promise} promise
*/
findHasMany: function (internalModel, link, relationship) {
var adapter = this.adapterFor(internalModel.modelName);
(false && _ember.default.assert('You tried to load a hasMany relationship but you have no adapter (for ' + internalModel.modelName + ')', adapter));
(false && _ember.default.assert('You tried to load a hasMany relationship from a specified \'link\' in the original payload but your adapter does not implement \'findHasMany\'', typeof adapter.findHasMany === 'function'));
return (0, _finders._findHasMany)(adapter, this, internalModel, link, relationship);
},
/**
@method findBelongsTo
@private
@param {InternalModel} internalModel
@param {any} link
@param {Relationship} relationship
@return {Promise} promise
*/
findBelongsTo: function (internalModel, link, relationship) {
var adapter = this.adapterFor(internalModel.modelName);
(false && _ember.default.assert('You tried to load a belongsTo relationship but you have no adapter (for ' + internalModel.modelName + ')', adapter));
(false && _ember.default.assert('You tried to load a belongsTo relationship from a specified \'link\' in the original payload but your adapter does not implement \'findBelongsTo\'', typeof adapter.findBelongsTo === 'function'));
return (0, _finders._findBelongsTo)(adapter, this, internalModel, link, relationship);
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Each time this method is called a new request is made through the adapter.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
---
If you do something like this:
```javascript
store.query('person', { page: 1 });
```
The call made to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?page=1"
Processing by Api::V1::PersonsController#index as HTML
Parameters: { "page"=>"1" }
```
---
If you do something like this:
```javascript
store.query('person', { ids: [1, 2, 3] });
```
The call to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
Processing by Api::V1::PersonsController#index as HTML
Parameters: { "ids" => ["1", "2", "3"] }
```
This method returns a promise, which is resolved with an
[`AdapterPopulatedRecordArray`](http://emberjs.com/api/data/classes/DS.AdapterPopulatedRecordArray.html)
once the server returns.
@since 1.13.0
@method query
@param {String} modelName
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise
*/
query: function (modelName, query) {
(false && _ember.default.assert('You need to pass a model name to the store\'s query method', isPresent(modelName)));
(false && _ember.default.assert('You need to pass a query hash to the store\'s query method', query));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
return this._query(normalizedModelName, query);
},
_query: function (modelName, query, array) {
(false && _ember.default.assert('You need to pass a model name to the store\'s query method', isPresent(modelName)));
(false && _ember.default.assert('You need to pass a query hash to the store\'s query method', query));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var adapter = this.adapterFor(modelName);
(false && _ember.default.assert('You tried to load a query but you have no adapter (for ' + modelName + ')', adapter));
(false && _ember.default.assert('You tried to load a query but your adapter does not implement \'query\'', typeof adapter.query === 'function'));
var pA = (0, _promiseProxies.promiseArray)((0, _finders._query)(adapter, this, modelName, query, array));
return pA;
},
/**
This method makes a request for one record, where the `id` is not known
beforehand (if the `id` is known, use [`findRecord`](#method_findRecord)
instead).
This method can be used when it is certain that the server will return a
single object for the primary data.
Each time this method is called a new request is made through the adapter.
Let's assume our API provides an endpoint for the currently logged in user
via:
```
// GET /api/current_user
{
user: {
id: 1234,
username: 'admin'
}
}
```
Since the specific `id` of the `user` is not known beforehand, we can use
`queryRecord` to get the user:
```javascript
store.queryRecord('user', {}).then(function(user) {
let username = user.get('username');
console.log(`Currently logged in as ${username}`);
});
```
The request is made through the adapters' `queryRecord`:
```app/adapters/user.js
import DS from 'ember-data';
export default DS.Adapter.extend({
queryRecord(modelName, query) {
return Ember.$.getJSON('/api/current_user');
}
});
```
Note: the primary use case for `store.queryRecord` is when a single record
is queried and the `id` is not known beforehand. In all other cases
`store.query` and using the first item of the array is likely the preferred
way:
```
// GET /users?username=unique
{
data: [{
id: 1234,
type: 'user',
attributes: {
username: "unique"
}
}]
}
```
```javascript
store.query('user', { username: 'unique' }).then(function(users) {
return users.get('firstObject');
}).then(function(user) {
let id = user.get('id');
});
```
This method returns a promise, which resolves with the found record.
If the adapter returns no data for the primary data of the payload, then
`queryRecord` resolves with `null`:
```
// GET /users?username=unique
{
data: null
}
```
```javascript
store.queryRecord('user', { username: 'unique' }).then(function(user) {
console.log(user); // null
});
```
@since 1.13.0
@method queryRecord
@param {String} modelName
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise which resolves with the found record or `null`
*/
queryRecord: function (modelName, query) {
(false && _ember.default.assert('You need to pass a model name to the store\'s queryRecord method', isPresent(modelName)));
(false && _ember.default.assert('You need to pass a query hash to the store\'s queryRecord method', query));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
var adapter = this.adapterFor(normalizedModelName);
(false && _ember.default.assert('You tried to make a query but you have no adapter (for ' + normalizedModelName + ')', adapter));
(false && _ember.default.assert('You tried to make a query but your adapter does not implement \'queryRecord\'', typeof adapter.queryRecord === 'function'));
return (0, _promiseProxies.promiseObject)((0, _finders._queryRecord)(adapter, this, modelName, query).then(function (internalModel) {
// the promise returned by store.queryRecord is expected to resolve with
// an instance of DS.Model
if (internalModel) {
return internalModel.getRecord();
}
return null;
}));
},
/**
`findAll` asks the adapter's `findAll` method to find the records for the
given type, and returns a promise which will resolve with all records of
this type present in the store, even if the adapter only returns a subset
of them.
```app/routes/authors.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findAll('author');
}
});
```
_When_ the returned promise resolves depends on the reload behavior,
configured via the passed `options` hash and the result of the adapter's
`shouldReloadAll` method.
### Reloading
If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to
`true`, then the returned promise resolves once the adapter returns data,
regardless if there are already records in the store:
```js
store.push({
data: {
id: 'first',
type: 'author'
}
});
// adapter#findAll resolves with
// [
// {
// id: 'second',
// type: 'author'
// }
// ]
store.findAll('author', { reload: true }).then(function(authors) {
authors.getEach('id'); // ['first', 'second']
});
```
If no reload is indicated via the abovementioned ways, then the promise
immediately resolves with all the records currently loaded in the store.
### Background Reloading
Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`,
then a background reload is started. Once this resolves, the array with
which the promise resolves, is updated automatically so it contains all the
records in the store:
```js
// app/adapters/application.js
export default DS.Adapter.extend({
shouldReloadAll(store, snapshotsArray) {
return false;
},
shouldBackgroundReloadAll(store, snapshotsArray) {
return true;
}
});
// ...
store.push({
data: {
id: 'first',
type: 'author'
}
});
let allAuthors;
store.findAll('author').then(function(authors) {
authors.getEach('id'); // ['first']
allAuthors = authors;
});
// later, once adapter#findAll resolved with
// [
// {
// id: 'second',
// type: 'author'
// }
// ]
allAuthors.getEach('id'); // ['first', 'second']
```
If you would like to force or prevent background reloading, you can set a
boolean value for `backgroundReload` in the options object for
`findAll`.
```app/routes/post/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.findAll('post', { backgroundReload: false });
}
});
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to you adapter via the `snapshotRecordArray`
```app/routes/posts.js
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findAll('post', {
adapterOptions: { subscribe: false }
});
}
});
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default MyCustomAdapter.extend({
findAll(store, type, sinceToken, snapshotRecordArray) {
if (snapshotRecordArray.adapterOptions.subscribe) {
// ...
}
// ...
}
});
```
See [peekAll](#method_peekAll) to get an array of current records in the
store, without waiting until a reload is finished.
### Retrieving Related Model Records
If you use an adapter such as Ember's default
[`JSONAPIAdapter`](http://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html)
that supports the [JSON API specification](http://jsonapi.org/) and if your server
endpoint supports the use of an
['include' query parameter](http://jsonapi.org/format/#fetching-includes),
you can use `findAll()` to automatically retrieve additional records related to
those requested by supplying an `include` parameter in the `options` object.
For example, given a `post` model that has a `hasMany` relationship with a `comment`
model, when we retrieve all of the post records we can have the server also return
all of the posts' comments in the same request:
```app/routes/posts.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.findAll('post', { include: 'comments' });
}
});
```
Multiple relationships can be requested using an `include` parameter consisting of a
comma-separated list (without white-space) while nested relationships can be specified
using a dot-separated sequence of relationship names. So to request both the posts'
comments and the authors of those comments the request would look like this:
```app/routes/posts.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.findAll('post', { include: 'comments,comments.author' });
}
});
```
See [query](#method_query) to only get a subset of records from the server.
@since 1.13.0
@method findAll
@param {String} modelName
@param {Object} options
@return {Promise} promise
*/
findAll: function (modelName, options) {
(false && _ember.default.assert('You need to pass a model name to the store\'s findAll method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
var fetch = this._fetchAll(normalizedModelName, this.peekAll(normalizedModelName), options);
return fetch;
},
/**
@method _fetchAll
@private
@param {DS.Model} modelName
@param {DS.RecordArray} array
@return {Promise} promise
*/
_fetchAll: function (modelName, array) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var adapter = this.adapterFor(modelName);
var sinceToken = this._internalModelsFor(modelName).metadata.since;
(false && _ember.default.assert('You tried to load all records but you have no adapter (for ' + modelName + ')', adapter));
(false && _ember.default.assert('You tried to load all records but your adapter does not implement \'findAll\'', typeof adapter.findAll === 'function'));
if (options.reload) {
set(array, 'isUpdating', true);
return (0, _promiseProxies.promiseArray)((0, _finders._findAll)(adapter, this, modelName, sinceToken, options));
}
var snapshotArray = array._createSnapshot(options);
if (adapter.shouldReloadAll(this, snapshotArray)) {
set(array, 'isUpdating', true);
return (0, _promiseProxies.promiseArray)((0, _finders._findAll)(adapter, this, modelName, sinceToken, options));
}
if (options.backgroundReload === false) {
return (0, _promiseProxies.promiseArray)(Promise.resolve(array));
}
if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) {
set(array, 'isUpdating', true);
(0, _finders._findAll)(adapter, this, modelName, sinceToken, options);
}
return (0, _promiseProxies.promiseArray)(Promise.resolve(array));
},
/**
@method _didUpdateAll
@param {String} modelName
@private
*/
_didUpdateAll: function (modelName) {
this.recordArrayManager._didUpdateAll(modelName);
},
didUpdateAll: function (modelName) {
(false && !(false) && _ember.default.deprecate('didUpdateAll was documented as private and will be removed in the next version of Ember Data.', false, { id: 'ember-data.didUpdateAll', until: '2.17.0' }));
return this._didUpdateAll(modelName);
},
/**
This method returns a filtered array that contains all of the
known records for a given type in the store.
Note that because it's just a filter, the result will contain any
locally created records of the type, however, it will not make a
request to the backend to retrieve additional records. If you
would like to request all the records from the backend please use
[store.findAll](#method_findAll).
Also note that multiple calls to `peekAll` for a given type will always
return the same `RecordArray`.
Example
```javascript
let localPosts = store.peekAll('post');
```
@since 1.13.0
@method peekAll
@param {String} modelName
@return {DS.RecordArray}
*/
peekAll: function (modelName) {
(false && _ember.default.assert('You need to pass a model name to the store\'s peekAll method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
return this.recordArrayManager.liveRecordArrayFor(normalizedModelName);
},
/**
This method unloads all records in the store.
It schedules unloading to happen during the next run loop.
Optionally you can pass a type which unload all records for a given type.
```javascript
store.unloadAll();
store.unloadAll('post');
```
@method unloadAll
@param {String} modelName
*/
unloadAll: function (modelName) {
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, !modelName || typeof modelName === 'string'));
if (arguments.length === 0) {
this._identityMap.clear();
} else {
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
this._internalModelsFor(normalizedModelName).clear();
}
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The filter function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
Example
```javascript
store.filter('post', function(post) {
return post.get('unread');
});
```
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query, which is the equivalent of calling
[query](#method_query) with that same query, to fetch additional records
from the server. The results returned by the server could then appear
in the filter if they match the filter function.
The query itself is not used to filter records, it's only sent to your
server for you to be able to do server-side filtering. The filter
function will be applied on the returned results regardless.
Example
```javascript
store.filter('post', { unread: true }, function(post) {
return post.get('unread');
}).then(function(unreadPosts) {
unreadPosts.get('length'); // 5
let unreadPost = unreadPosts.objectAt(0);
unreadPost.set('unread', false);
unreadPosts.get('length'); // 4
});
```
@method filter
@private
@param {String} modelName
@param {Object} query optional query
@param {Function} filter
@return {DS.PromiseArray}
@deprecated
*/
filter: function (modelName, query, filter) {
(false && _ember.default.assert('You need to pass a model name to the store\'s filter method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
if (!ENV.ENABLE_DS_FILTER) {
(false && _ember.default.assert('The filter API has been moved to a plugin. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page. https://github.com/ember-data/ember-data-filter', false));
}
var promise = void 0;
var length = arguments.length;
var array = void 0;
var hasQuery = length === 3;
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
// allow an optional server query
if (hasQuery) {
promise = this.query(normalizedModelName, query);
} else if (arguments.length === 2) {
filter = query;
}
if (hasQuery) {
array = this.recordArrayManager.createFilteredRecordArray(normalizedModelName, filter, query);
} else {
array = this.recordArrayManager.createFilteredRecordArray(normalizedModelName, filter);
}
promise = promise || Promise.resolve(array);
return (0, _promiseProxies.promiseArray)(promise.then(function () {
return array;
}, null, 'DS: Store#filter of ' + normalizedModelName));
},
/**
This method has been deprecated and is an alias for store.hasRecordForId, which should
be used instead.
@deprecated
@method recordIsLoaded
@param {String} modelName
@param {string} id
@return {boolean}
*/
recordIsLoaded: function (modelName, id) {
(false && !(false) && _ember.default.deprecate('Use of recordIsLoaded is deprecated, use hasRecordForId instead.', false, {
id: 'ds.store.recordIsLoaded',
until: '3.0'
}));
return this.hasRecordForId(modelName, id);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {InternalModel} internalModel
@param {Resolver} resolver
@param {Object} options
*/
scheduleSave: function (internalModel, resolver, options) {
var snapshot = internalModel.createSnapshot(options);
internalModel.flushChangedAttributes();
internalModel.adapterWillCommit();
this._pendingSave.push({
snapshot: snapshot,
resolver: resolver
});
emberRun.once(this, this.flushPendingSave);
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function () {
var pending = this._pendingSave.slice();
this._pendingSave = [];
for (var i = 0, j = pending.length; i < j; i++) {
var pendingItem = pending[i];
var snapshot = pendingItem.snapshot;
var resolver = pendingItem.resolver;
var internalModel = snapshot._internalModel;
var adapter = this.adapterFor(internalModel.modelName);
var operation = void 0;
if (internalModel.currentState.stateName === 'root.deleted.saved') {
return resolver.resolve();
} else if (internalModel.isNew()) {
operation = 'createRecord';
} else if (internalModel.isDeleted()) {
operation = 'deleteRecord';
} else {
operation = 'updateRecord';
}
resolver.resolve(_commit(adapter, this, operation, snapshot));
}
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {InternalModel} internalModel the in-flight internal model
@param {Object} data optional data (see above)
*/
didSaveRecord: function (internalModel, dataArg) {
var data = void 0;
if (dataArg) {
data = dataArg.data;
}
if (data) {
// normalize relationship IDs into records
this.updateId(internalModel, data);
this._setupRelationshipsForModel(internalModel, data);
} else {
(false && _ember.default.assert('Your ' + internalModel.modelName + ' record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.', internalModel.id));
}
//We first make sure the primary data has been updated
//TODO try to move notification to the user to the end of the runloop
internalModel.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {InternalModel} internalModel
@param {Object} errors
*/
recordWasInvalid: function (internalModel, errors) {
internalModel.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {InternalModel} internalModel
@param {Error} error
*/
recordWasError: function (internalModel, error) {
internalModel.adapterDidError(error);
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {InternalModel} internalModel
@param {Object} data
*/
updateId: function (internalModel, data) {
var oldId = internalModel.id;
var modelName = internalModel.modelName;
var id = (0, _coerceId.default)(data.id);
// ID absolutely can't be missing if the oldID is empty (missing Id in response for a new record)
(false && _ember.default.assert('\'' + modelName + '\' was saved to the server, but the response does not have an id and your record does not either.', !(id === null && oldId === null)));
// ID absolutely can't be different than oldID if oldID is not null
(false && _ember.default.assert('\'' + modelName + ':' + oldId + '\' was saved to the server, but the response returned the new id \'' + id + '\'. The store cannot assign a new id to a record that already has an id.', !(oldId !== null && id !== oldId)));
// ID can be null if oldID is not null (altered ID in response for a record)
// however, this is more than likely a developer error.
if (oldId !== null && id === null) {
(false && _ember.default.warn('Your ' + modelName + ' record was saved to the server, but the response does not have an id.', !(oldId !== null && id === null)));
return;
}
this._internalModelsFor(internalModel.modelName).set(id, internalModel);
internalModel.setId(id);
},
/**
Returns a map of IDs to client IDs for a given modelName.
@method _internalModelsFor
@private
@param {String} modelName
@return {Object} recordMap
*/
_internalModelsFor: function (modelName) {
return this._identityMap.retrieve(modelName);
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {Object} data
*/
_load: function (data) {
var internalModel = this._internalModelForId(data.type, data.id);
internalModel.setupData(data);
this.recordArrayManager.recordDidChange(internalModel);
return internalModel;
},
/*
In case someone defined a relationship to a mixin, for example:
```
let Comment = DS.Model.extend({
owner: belongsTo('commentable'. { polymorphic: true })
});
let Commentable = Ember.Mixin.create({
comments: hasMany('comment')
});
```
we want to look up a Commentable class which has all the necessary
relationship metadata. Thus, we look up the mixin and create a mock
DS.Model, so we can access the relationship CPs of the mixin (`comments`)
in this case
@private
*/
_modelForMixin: function (normalizedModelName) {
// container.registry = 2.1
// container._registry = 1.11 - 2.0
// container = < 1.11
var owner = (0, _utils.getOwner)(this);
var mixin = void 0;
if (owner.factoryFor) {
var MaybeMixin = owner.factoryFor('mixin:' + normalizedModelName);
mixin = MaybeMixin && MaybeMixin.class;
} else {
mixin = owner._lookupFactory('mixin:' + normalizedModelName);
}
if (mixin) {
var ModelForMixin = _model.default.extend(mixin);
ModelForMixin.reopenClass({
__isMixin: true,
__mixin: mixin
});
//Cache the class as a model
owner.register('model:' + normalizedModelName, ModelForMixin);
}
return this.modelFactoryFor(normalizedModelName);
},
/**
Returns the model class for the particular `modelName`.
The class of a model might be useful if you want to get a list of all the
relationship names of the model, see
[`relationshipNames`](http://emberjs.com/api/data/classes/DS.Model.html#property_relationshipNames)
for example.
@method modelFor
@param {String} modelName
@return {DS.Model}
*/
modelFor: function (modelName) {
(false && _ember.default.assert('You need to pass a model name to the store\'s modelFor method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
return this._modelFor(normalizedModelName);
},
/*
@private
*/
_modelFor: function (modelName) {
var maybeFactory = this._modelFactoryFor(modelName);
// for factorFor factory/class split
return maybeFactory.class ? maybeFactory.class : maybeFactory;
},
_modelFactoryFor: function (modelName) {
var factory = this._modelFactoryCache[modelName];
if (!factory) {
factory = this.modelFactoryFor(modelName);
if (!factory) {
//Support looking up mixins as base types for polymorphic relationships
factory = this._modelForMixin(modelName);
}
if (!factory) {
throw new EmberError('No model was found for \'' + modelName + '\'');
}
// interopt with the future
var klass = (0, _utils.getOwner)(this).factoryFor ? factory.class : factory;
(false && _ember.default.assert('\'' + inspect(klass) + '\' does not appear to be an ember-data model', klass.isModel));
// TODO: deprecate this
klass.modelName = klass.modelName || modelName;
this._modelFactoryCache[modelName] = factory;
}
return factory;
},
/*
@private
*/
modelFactoryFor: function (modelName) {
(false && _ember.default.assert('You need to pass a model name to the store\'s modelFactoryFor method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
var owner = (0, _utils.getOwner)(this);
if (owner.factoryFor) {
return owner.factoryFor('model:' + normalizedModelName);
} else {
return owner._lookupFactory('model:' + normalizedModelName);
}
},
/**
Push some data for a given type into the store.
This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments:
- record's `type` should always be in singular, dasherized form
- members (properties) should be camelCased
[Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level):
```js
store.push({
data: {
// primary data for single record of type `Person`
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
}
});
```
[Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7)
`data` property can also hold an array (of records):
```js
store.push({
data: [
// an array of records
{
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
},
{
id: '2',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
}
}
]
});
```
[Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355)
There are some typical properties for `JSONAPI` payload:
* `id` - mandatory, unique record's key
* `type` - mandatory string which matches `model`'s dasherized name in singular form
* `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model
* `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`):
- [`links`](http://jsonapi.org/format/#document-links)
- [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data
- [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship
For this model:
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
data: [
{
id: '2',
type: 'person'
},
{
id: '3',
type: 'person'
},
{
id: '4',
type: 'person'
}
]
}
}
}
}
```
[Demo.](http://ember-twiddle.com/343e1735e034091f5bde)
To represent the children relationship as a URL:
```js
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
links: {
related: '/people/1/children'
}
}
}
}
}
```
If you're streaming data or implementing an adapter, make sure
that you have converted the incoming data into this form. The
store's [normalize](#method_normalize) method is a convenience
helper for converting a json payload into the form Ember Data
expects.
```js
store.push(store.normalize('person', data));
```
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {Object} data
@return {DS.Model|Array} the record(s) that was created or
updated.
*/
push: function (data) {
var pushed = this._push(data);
if (Array.isArray(pushed)) {
var records = pushed.map(function (internalModel) {
return internalModel.getRecord();
});
return records;
}
if (pushed === null) {
return null;
}
var record = pushed.getRecord();
return record;
},
/*
Push some data in the form of a json-api document into the store,
without creating materialized records.
@method _push
@private
@param {Object} jsonApiDoc
@return {DS.InternalModel|Array<DS.InternalModel>} pushed InternalModel(s)
*/
_push: function (jsonApiDoc) {
var _this = this;
var internalModelOrModels = this._backburner.join(function () {
var included = jsonApiDoc.included;
var i = void 0,
length = void 0;
if (included) {
for (i = 0, length = included.length; i < length; i++) {
_this._pushInternalModel(included[i]);
}
}
if (Array.isArray(jsonApiDoc.data)) {
length = jsonApiDoc.data.length;
var internalModels = new Array(length);
for (i = 0; i < length; i++) {
internalModels[i] = _this._pushInternalModel(jsonApiDoc.data[i]);
}
return internalModels;
}
if (jsonApiDoc.data === null) {
return null;
}
(false && _ember.default.assert('Expected an object in the \'data\' property in a call to \'push\' for ' + jsonApiDoc.type + ', but was ' + typeOf(jsonApiDoc.data), typeOf(jsonApiDoc.data) === 'object'));
return _this._pushInternalModel(jsonApiDoc.data);
});
return internalModelOrModels;
},
_hasModelFor: function (modelName) {
var owner = (0, _utils.getOwner)(this);
modelName = (0, _normalizeModelName.default)(modelName);
if (owner.factoryFor) {
return !!owner.factoryFor('model:' + modelName);
} else {
return !!owner._lookupFactory('model:' + modelName);
}
},
_pushInternalModel: function (data) {
var modelName = data.type;
(false && _ember.default.assert('You must include an \'id\' for ' + modelName + ' in an object passed to \'push\'', data.id !== null && data.id !== undefined && data.id !== ''));
(false && _ember.default.assert('You tried to push data with a type \'' + modelName + '\' but no model could be found with that name.', this._hasModelFor(modelName)));
if (false) {
// If ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload
// contains unknown attributes or relationships, log a warning.
if (ENV.DS_WARN_ON_UNKNOWN_KEYS) {
var modelClass = this._modelFor(modelName);
// Check unknown attributes
var unknownAttributes = Object.keys(data.attributes || {}).filter(function (key) {
return !get(modelClass, 'fields').has(key);
});
var unknownAttributesMessage = 'The payload for \'' + modelName + '\' contains these unknown attributes: ' + unknownAttributes + '. Make sure they\'ve been defined in your model.';
(false && _ember.default.warn(unknownAttributesMessage, unknownAttributes.length === 0, { id: 'ds.store.unknown-keys-in-payload' }));
// Check unknown relationships
var unknownRelationships = Object.keys(data.relationships || {}).filter(function (key) {
return !get(modelClass, 'fields').has(key);
});
var unknownRelationshipsMessage = 'The payload for \'' + modelName + '\' contains these unknown relationships: ' + unknownRelationships + '. Make sure they\'ve been defined in your model.';
(false && _ember.default.warn(unknownRelationshipsMessage, unknownRelationships.length === 0, { id: 'ds.store.unknown-keys-in-payload' }));
}
}
// Actually load the record into the store.
var internalModel = this._load(data);
this._setupRelationshipsForModel(internalModel, data);
return internalModel;
},
_setupRelationshipsForModel: function (internalModel, data) {
if (data.relationships === undefined) {
return;
}
if (this._pushedInternalModels.push(internalModel, data) !== 2) {
return;
}
this._backburner.schedule('normalizeRelationships', this, this._setupRelationships);
},
_setupRelationships: function () {
var pushed = this._pushedInternalModels;
// Cache the inverse maps for each modelClass that we visit during this
// payload push. In the common case where we are pushing many more
// instances than types we want to minimize the cost of looking up the
// inverse map and the overhead of Ember.get adds up.
var modelNameToInverseMap = Object.create(null);
for (var i = 0, l = pushed.length; i < l; i += 2) {
// This will convert relationships specified as IDs into DS.Model instances
// (possibly unloaded) and also create the data structures used to track
// relationships.
var internalModel = pushed[i];
var data = pushed[i + 1];
setupRelationships(this, internalModel, data, modelNameToInverseMap);
}
pushed.length = 0;
},
/**
Push some raw data into the store.
This method can be used both to push in brand new
records, as well as to update existing records. You
can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.ActiveModelSerializer;
```
```js
let pushData = {
posts: [
{ id: 1, post_title: "Great post", comment_ids: [2] }
],
comments: [
{ id: 2, comment_body: "Insightful comment" }
]
}
store.pushPayload(pushData);
```
By default, the data will be deserialized using a default
serializer (the application serializer if it exists).
Alternatively, `pushPayload` will accept a model type which
will determine which serializer will process the payload.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.ActiveModelSerializer;
```
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer;
```
```js
store.pushPayload('comment', pushData); // Will use the application serializer
store.pushPayload('post', pushData); // Will use the post serializer
```
@method pushPayload
@param {String} modelName Optionally, a model type used to determine which serializer will be used
@param {Object} inputPayload
*/
pushPayload: function (modelName, inputPayload) {
var serializer = void 0;
var payload = void 0;
if (!inputPayload) {
payload = modelName;
serializer = defaultSerializer(this);
(false && _ember.default.assert('You cannot use \'store#pushPayload\' without a modelName unless your default serializer defines \'pushPayload\'', typeof serializer.pushPayload === 'function'));
} else {
payload = inputPayload;
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
serializer = this.serializerFor(normalizedModelName);
}
if ((0, _features.default)('ds-pushpayload-return')) {
return serializer.pushPayload(this, payload);
} else {
serializer.pushPayload(this, payload);
}
},
/**
`normalize` converts a json payload into the normalized form that
[push](#method_push) expects.
Example
```js
socket.on('message', function(message) {
let modelName = message.model;
let data = message.data;
store.push(store.normalize(modelName, data));
});
```
@method normalize
@param {String} modelName The name of the model type for this payload
@param {Object} payload
@return {Object} The normalized payload
*/
normalize: function (modelName, payload) {
(false && _ember.default.assert('You need to pass a model name to the store\'s normalize method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + inspect(modelName), typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
var serializer = this.serializerFor(normalizedModelName);
var model = this._modelFor(normalizedModelName);
return serializer.normalize(model, payload);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method _buildInternalModel
@private
@param {String} modelName
@param {String} id
@param {Object} data
@return {InternalModel} internal model
*/
_buildInternalModel: function (modelName, id, data) {
(false && _ember.default.assert('You can no longer pass a modelClass as the first argument to store._buildInternalModel. Pass modelName instead.', typeof modelName === 'string'));
var recordMap = this._internalModelsFor(modelName);
(false && _ember.default.assert('The id ' + id + ' has already been used with another record for modelClass \'' + modelName + '\'.', !id || !recordMap.get(id)));
// lookupFactory should really return an object that creates
// instances with the injections applied
var internalModel = new _internalModel5.default(modelName, id, this, data);
recordMap.add(internalModel, id);
return internalModel;
},
buildInternalModel: function (modelName, id, data) {
(false && !(false) && _ember.default.deprecate('buildInternalModel was documented as private and will be removed in the next version of Ember Data.', false, { id: 'ember-data.buildInternalModel', until: '2.17.0' }));
return this._buildInternalModel(modelName, id, data);
},
//Called by the state machine to notify the store that the record is ready to be interacted with
recordWasLoaded: function (record) {
this.recordArrayManager.recordWasLoaded(record);
},
// ...............
// . DESTRUCTION .
// ...............
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method _removeFromIdMap
@private
@param {InternalModel} internalModel
*/
_removeFromIdMap: function (internalModel) {
var recordMap = this._internalModelsFor(internalModel.modelName);
var id = internalModel.id;
recordMap.remove(internalModel, id);
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns an instance of the adapter for a given type. For
example, `adapterFor('person')` will return an instance of
`App.PersonAdapter`.
If no `App.PersonAdapter` is found, this method will look
for an `App.ApplicationAdapter` (the default adapter for
your entire application).
If no `App.ApplicationAdapter` is found, it will return
the value of the `defaultAdapter`.
@method adapterFor
@public
@param {String} modelName
@return DS.Adapter
*/
adapterFor: function (modelName) {
(false && _ember.default.assert('You need to pass a model name to the store\'s adapterFor method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
return this._instanceCache.get('adapter', normalizedModelName);
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
if no `App.ApplicationSerializer` is found, it will attempt
to get the `defaultSerializer` from the `PersonAdapter`
(`adapterFor('person')`).
If a serializer cannot be found on the adapter, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@public
@param {String} modelName the record to serialize
@return {DS.Serializer}
*/
serializerFor: function (modelName) {
(false && _ember.default.assert('You need to pass a model name to the store\'s serializerFor method', isPresent(modelName)));
(false && _ember.default.assert('Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string'));
var normalizedModelName = (0, _normalizeModelName.default)(modelName);
return this._instanceCache.get('serializer', normalizedModelName);
},
lookupAdapter: function (name) {
(false && !(false) && _ember.default.deprecate('Use of lookupAdapter is deprecated, use adapterFor instead.', false, {
id: 'ds.store.lookupAdapter',
until: '3.0'
}));
return this.adapterFor(name);
},
lookupSerializer: function (name) {
(false && !(false) && _ember.default.deprecate('Use of lookupSerializer is deprecated, use serializerFor instead.', false, {
id: 'ds.store.lookupSerializer',
until: '3.0'
}));
return this.serializerFor(name);
},
willDestroy: function () {
this._super.apply(this, arguments);
this._pushedInternalModels = null;
this.recordArrayManager.destroy();
this._instanceCache.destroy();
this.unloadAll();
},
_updateRelationshipState: function (relationship) {
var _this2 = this;
if (this._updatedRelationships.push(relationship) !== 1) {
return;
}
this._backburner.join(function () {
_this2._backburner.schedule('syncRelationships', _this2, _this2._flushUpdatedRelationships);
});
},
_flushUpdatedRelationships: function () {
var updated = this._updatedRelationships;
for (var i = 0, l = updated.length; i < l; i++) {
updated[i].flushCanonical();
}
updated.length = 0;
},
_updateInternalModel: function (internalModel) {
if (this._updatedInternalModels.push(internalModel) !== 1) {
return;
}
emberRun.schedule('actions', this, this._flushUpdatedInternalModels);
},
_flushUpdatedInternalModels: function () {
var updated = this._updatedInternalModels;
for (var i = 0, l = updated.length; i < l; i++) {
updated[i]._triggerDeferredTriggers();
}
updated.length = 0;
},
_pushResourceIdentifier: function (relationship, resourceIdentifier) {
if (isNone(resourceIdentifier)) {
return;
}
(false && _ember.default.assert('A ' + relationship.internalModel.modelName + ' record was pushed into the store with the value of ' + relationship.key + ' being ' + inspect(resourceIdentifier) + ', but ' + relationship.key + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Array.isArray(resourceIdentifier)));
//TODO:Better asserts
return this._internalModelForId(resourceIdentifier.type, resourceIdentifier.id);
},
_pushResourceIdentifiers: function (relationship, resourceIdentifiers) {
if (isNone(resourceIdentifiers)) {
return;
}
(false && _ember.default.assert('A ' + relationship.internalModel.modelName + ' record was pushed into the store with the value of ' + relationship.key + ' being \'' + inspect(resourceIdentifiers) + '\', but ' + relationship.key + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Array.isArray(resourceIdentifiers)));
var _internalModels = new Array(resourceIdentifiers.length);
for (var i = 0; i < resourceIdentifiers.length; i++) {
_internalModels[i] = this._pushResourceIdentifier(relationship, resourceIdentifiers[i]);
}
return _internalModels;
}
});
// Delegation to the adapter and promise management
function defaultSerializer(store) {
return store.serializerFor('application');
}
function _commit(adapter, store, operation, snapshot) {
var internalModel = snapshot._internalModel;
var modelName = snapshot.modelName;
var modelClass = store._modelFor(modelName);
(false && _ember.default.assert('You tried to update a record but you have no adapter (for ' + modelName + ')', adapter));
(false && _ember.default.assert('You tried to update a record but your adapter (for ' + modelName + ') does not implement \'' + operation + '\'', typeof adapter[operation] === 'function'));
var promise = adapter[operation](store, modelClass, snapshot);
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName);
var label = 'DS: Extract and notify about ' + operation + ' completion of ' + internalModel;
(false && _ember.default.assert('Your adapter\'s \'' + operation + '\' method must return a value, but it returned \'undefined\'', promise !== undefined));
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, internalModel));
return promise.then(function (adapterPayload) {
/*
Note to future spelunkers hoping to optimize.
We rely on this `run` to create a run loop if needed
that `store._push` and `store.didSaveRecord` will both share.
We use `join` because it is often the case that we
have an outer run loop available still from the first
call to `store._push`;
*/
store._backburner.join(function () {
var payload = void 0,
data = void 0;
if (adapterPayload) {
payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, snapshot.id, operation);
if (payload.included) {
store._push({ data: null, included: payload.included });
}
data = payload.data;
}
store.didSaveRecord(internalModel, { data: data });
});
return internalModel;
}, function (error) {
if (error instanceof _errors.InvalidError) {
var errors = serializer.extractErrors(store, modelClass, error, snapshot.id);
store.recordWasInvalid(internalModel, errors);
} else {
store.recordWasError(internalModel, error);
}
throw error;
}, label);
}
function isInverseRelationshipInitialized(store, internalModel, data, key, modelNameToInverseMap) {
var relationshipData = data.relationships[key].data;
if (!relationshipData) {
// can't check inverse for eg { comments: { links: { related: URL }}}
return false;
}
var inverseMap = modelNameToInverseMap[internalModel.modelName];
if (!inverseMap) {
inverseMap = modelNameToInverseMap[internalModel.modelName] = get(internalModel.type, 'inverseMap');
}
var inverseRelationshipMetadata = inverseMap[key];
if (inverseRelationshipMetadata === undefined) {
inverseRelationshipMetadata = internalModel.type.inverseFor(key, store);
}
if (!inverseRelationshipMetadata) {
return false;
}
var _inverseRelationshipM = inverseRelationshipMetadata,
inverseRelationshipName = _inverseRelationshipM.name;
if (Array.isArray(relationshipData)) {
for (var i = 0; i < relationshipData.length; ++i) {
var inverseInternalModel = store._internalModelsFor(relationshipData[i].type).get(relationshipData[i].id);
if (inverseInternalModel && inverseInternalModel._relationships.has(inverseRelationshipName)) {
return true;
}
}
return false;
} else {
var _inverseInternalModel = store._internalModelsFor(relationshipData.type).get(relationshipData.id);
return _inverseInternalModel && _inverseInternalModel._relationships.has(inverseRelationshipName);
}
}
function setupRelationships(store, internalModel, data, modelNameToInverseMap) {
var relationships = internalModel._relationships;
internalModel.type.eachRelationship(function (relationshipName) {
if (!data.relationships[relationshipName]) {
return;
}
var relationshipRequiresNotification = relationships.has(relationshipName) || isInverseRelationshipInitialized(store, internalModel, data, relationshipName, modelNameToInverseMap);
if (relationshipRequiresNotification) {
var relationshipData = data.relationships[relationshipName];
relationships.get(relationshipName).push(relationshipData);
}
// in debug, assert payload validity eagerly
if (false) {
var relationshipMeta = get(internalModel.type, 'relationshipsByName').get(relationshipName);
var _relationshipData = data.relationships[relationshipName];
if (!_relationshipData || !relationshipMeta) {
return;
}
if (_relationshipData.links) {
var isAsync = relationshipMeta.options && relationshipMeta.options.async !== false;
(false && _ember.default.warn('You pushed a record of type \'' + internalModel.type.modelName + '\' with a relationship \'' + relationshipName + '\' configured as \'async: false\'. You\'ve included a link but no primary data, this may be an error in your payload.', isAsync || _relationshipData.data, {
id: 'ds.store.push-link-for-sync-relationship'
}));
} else if (_relationshipData.data) {
if (relationshipMeta.kind === 'belongsTo') {
(false && _ember.default.assert('A ' + internalModel.type.modelName + ' record was pushed into the store with the value of ' + relationshipName + ' being ' + inspect(_relationshipData.data) + ', but ' + relationshipName + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Array.isArray(_relationshipData.data)));
} else if (relationshipMeta.kind === 'hasMany') {
(false && _ember.default.assert('A ' + internalModel.type.modelName + ' record was pushed into the store with the value of ' + relationshipName + ' being \'' + inspect(_relationshipData.data) + '\', but ' + relationshipName + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Array.isArray(_relationshipData.data)));
}
}
}
});
}
exports.Store = Store;
exports.default = Store;
});
define('ember-data/-private/system/store/common', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports._bind = _bind;
exports._guard = _guard;
exports._objectIsAlive = _objectIsAlive;
var get = _ember.default.get;
function _bind(fn) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return function () {
return fn.apply(undefined, args);
};
}
function _guard(promise, test) {
var guarded = promise['finally'](function () {
if (!test()) {
guarded._subscribers.length = 0;
}
});
return guarded;
}
function _objectIsAlive(object) {
return !(get(object, "isDestroyed") || get(object, "isDestroying"));
}
});
define('ember-data/-private/system/store/container-instance-cache', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var set = _ember.default.set;
var ContainerInstanceCache = function () {
function ContainerInstanceCache(owner, store) {
_classCallCheck(this, ContainerInstanceCache);
this.isDestroying = false;
this.isDestroyed = false;
this._owner = owner;
this._store = store;
this._namespaces = {
adapter: Object.create(null),
serializer: Object.create(null)
};
}
ContainerInstanceCache.prototype.get = function get(namespace, preferredKey) {
var cache = this._namespaces[namespace];
if (cache[preferredKey]) {
return cache[preferredKey];
}
var preferredLookupKey = namespace + ':' + preferredKey;
var instance = this._instanceFor(preferredLookupKey) || this._findInstance(namespace, this._fallbacksFor(namespace, preferredKey));
if (instance) {
cache[preferredKey] = instance;
set(instance, 'store', this._store);
}
return cache[preferredKey];
};
ContainerInstanceCache.prototype._fallbacksFor = function _fallbacksFor(namespace, preferredKey) {
if (namespace === 'adapter') {
return ['application', this._store.get('adapter'), '-json-api'];
}
// serializer
return ['application', this.get('adapter', preferredKey).get('defaultSerializer'), '-default'];
};
ContainerInstanceCache.prototype._findInstance = function _findInstance(namespace, fallbacks) {
var cache = this._namespaces[namespace];
for (var i = 0, length = fallbacks.length; i < length; i++) {
var fallback = fallbacks[i];
if (cache[fallback]) {
return cache[fallback];
}
var lookupKey = namespace + ':' + fallback;
var instance = this._instanceFor(lookupKey);
if (instance) {
cache[fallback] = instance;
return instance;
}
}
};
ContainerInstanceCache.prototype._instanceFor = function _instanceFor(key) {
return this._owner.lookup(key);
};
ContainerInstanceCache.prototype.destroyCache = function destroyCache(cache) {
var cacheEntries = Object.keys(cache);
for (var i = 0, length = cacheEntries.length; i < length; i++) {
var cacheKey = cacheEntries[i];
var cacheEntry = cache[cacheKey];
if (cacheEntry) {
cacheEntry.destroy();
}
}
};
ContainerInstanceCache.prototype.destroy = function destroy() {
this.isDestroying = true;
this.destroyCache(this._namespaces.adapter);
this.destroyCache(this._namespaces.serializer);
this.isDestroyed = true;
};
ContainerInstanceCache.prototype.toString = function toString() {
return 'ContainerInstanceCache';
};
return ContainerInstanceCache;
}();
exports.default = ContainerInstanceCache;
});
define('ember-data/-private/system/store/finders', ['exports', 'ember', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers'], function (exports, _ember, _common, _serializerResponse, _serializers) {
'use strict';
exports.__esModule = true;
exports._find = _find;
exports._findMany = _findMany;
exports._findHasMany = _findHasMany;
exports._findBelongsTo = _findBelongsTo;
exports._findAll = _findAll;
exports._query = _query;
exports._queryRecord = _queryRecord;
var Promise = _ember.default.RSVP.Promise;
function payloadIsNotBlank(adapterPayload) {
if (Array.isArray(adapterPayload)) {
return true;
} else {
return Object.keys(adapterPayload || {}).length;
}
}
function _find(adapter, store, modelClass, id, internalModel, options) {
var snapshot = internalModel.createSnapshot(options);
var modelName = internalModel.modelName;
var promise = adapter.findRecord(store, modelClass, id, snapshot);
var label = 'DS: Handle Adapter#findRecord of \'' + modelName + '\' with id: \'' + id + '\'';
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
return promise.then(function (adapterPayload) {
(false && _ember.default.assert('You made a \'findRecord\' request for a \'' + modelName + '\' with id \'' + id + '\', but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload)));
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName);
var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, id, 'findRecord');
(false && _ember.default.assert('Ember Data expected the primary data returned from a \'findRecord\' response to be an object but instead it found an array.', !Array.isArray(payload.data)));
(false && _ember.default.warn('You requested a record of type \'' + modelName + '\' with id \'' + id + '\' but the adapter returned a payload with primary data having an id of \'' + payload.data.id + '\'. Use \'store.findRecord()\' when the requested id is the same as the one returned by the adapter. In other cases use \'store.queryRecord()\' instead http://emberjs.com/api/data/classes/DS.Store.html#method_queryRecord', payload.data.id === id, {
id: 'ds.store.findRecord.id-mismatch'
}));
return store._push(payload);
}, function (error) {
internalModel.notFound();
if (internalModel.isEmpty()) {
internalModel.unloadRecord();
}
throw error;
}, 'DS: Extract payload of \'' + modelName + '\'');
}
function _findMany(adapter, store, modelName, ids, internalModels) {
var snapshots = _ember.default.A(internalModels).invoke('createSnapshot');
var modelClass = store.modelFor(modelName); // `adapter.findMany` gets the modelClass still
var promise = adapter.findMany(store, modelClass, ids, snapshots);
var label = 'DS: Handle Adapter#findMany of \'' + modelName + '\'';
if (promise === undefined) {
throw new Error('adapter.findMany returned undefined, this was very likely a mistake');
}
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
return promise.then(function (adapterPayload) {
(false && _ember.default.assert('You made a \'findMany\' request for \'' + modelName + '\' records with ids \'[' + ids + ']\', but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload)));
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName);
var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findMany');
return store._push(payload);
}, null, 'DS: Extract payload of ' + modelName);
}
function _findHasMany(adapter, store, internalModel, link, relationship) {
var snapshot = internalModel.createSnapshot();
var modelClass = store.modelFor(relationship.type);
var promise = adapter.findHasMany(store, snapshot, link, relationship);
var label = 'DS: Handle Adapter#findHasMany of \'' + internalModel.modelName + '\' : \'' + relationship.type + '\'';
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, internalModel));
return promise.then(function (adapterPayload) {
(false && _ember.default.assert('You made a \'findHasMany\' request for a ' + internalModel.modelName + '\'s \'' + relationship.key + '\' relationship, using link \'' + link + '\' , but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload)));
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, relationship.type);
var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findHasMany');
var internalModelArray = store._push(payload);
internalModelArray.meta = payload.meta;
return internalModelArray;
}, null, 'DS: Extract payload of \'' + internalModel.modelName + '\' : hasMany \'' + relationship.type + '\'');
}
function _findBelongsTo(adapter, store, internalModel, link, relationship) {
var snapshot = internalModel.createSnapshot();
var modelClass = store.modelFor(relationship.type);
var promise = adapter.findBelongsTo(store, snapshot, link, relationship);
var label = 'DS: Handle Adapter#findBelongsTo of ' + internalModel.modelName + ' : ' + relationship.type;
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, internalModel));
return promise.then(function (adapterPayload) {
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, relationship.type);
var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findBelongsTo');
if (!payload.data) {
return null;
}
return store._push(payload);
}, null, 'DS: Extract payload of ' + internalModel.modelName + ' : ' + relationship.type);
}
function _findAll(adapter, store, modelName, sinceToken, options) {
var modelClass = store.modelFor(modelName); // adapter.findAll depends on the class
var recordArray = store.peekAll(modelName);
var snapshotArray = recordArray._createSnapshot(options);
var promise = adapter.findAll(store, modelClass, sinceToken, snapshotArray);
var label = "DS: Handle Adapter#findAll of " + modelClass;
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
return promise.then(function (adapterPayload) {
(false && _ember.default.assert('You made a \'findAll\' request for \'' + modelName + '\' records, but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload)));
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName);
var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findAll');
store._push(payload);
store._didUpdateAll(modelName);
return recordArray;
}, null, 'DS: Extract payload of findAll ${modelName}');
}
function _query(adapter, store, modelName, query, recordArray) {
var modelClass = store.modelFor(modelName); // adapter.query needs the class
var promise = void 0;
if (adapter.query.length > 3) {
recordArray = recordArray || store.recordArrayManager.createAdapterPopulatedRecordArray(modelName, query);
promise = adapter.query(store, modelClass, query, recordArray);
} else {
promise = adapter.query(store, modelClass, query);
}
var label = 'DS: Handle Adapter#query of ' + modelClass;
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
return promise.then(function (adapterPayload) {
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName);
var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'query');
var internalModels = store._push(payload);
(false && _ember.default.assert('The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.', Array.isArray(internalModels)));
if (recordArray) {
recordArray._setInternalModels(internalModels, payload);
} else {
recordArray = store.recordArrayManager.createAdapterPopulatedRecordArray(modelName, query, internalModels, payload);
}
return recordArray;
}, null, 'DS: Extract payload of query ' + modelName);
}
function _queryRecord(adapter, store, modelName, query) {
var modelClass = store.modelFor(modelName); // adapter.queryRecord needs the class
var promise = adapter.queryRecord(store, modelClass, query);
var label = 'DS: Handle Adapter#queryRecord of ' + modelName;
promise = Promise.resolve(promise, label);
promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store));
return promise.then(function (adapterPayload) {
var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName);
var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'queryRecord');
(false && _ember.default.assert('Expected the primary data returned by the serializer for a \'queryRecord\' response to be a single object or null but instead it was an array.', !Array.isArray(payload.data), {
id: 'ds.store.queryRecord-array-response'
}));
return store._push(payload);
}, null, 'DS: Extract payload of queryRecord ' + modelName);
}
});
define('ember-data/-private/system/store/serializer-response', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.validateDocumentStructure = validateDocumentStructure;
exports.normalizeResponseHelper = normalizeResponseHelper;
/*
This is a helper method that validates a JSON API top-level document
The format of a document is described here:
http://jsonapi.org/format/#document-top-level
@method validateDocumentStructure
@param {Object} doc JSON API document
@return {array} An array of errors found in the document structure
*/
function validateDocumentStructure(doc) {
var errors = [];
if (!doc || typeof doc !== 'object') {
errors.push('Top level of a JSON API document must be an object');
} else {
if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) {
errors.push('One or more of the following keys must be present: "data", "errors", "meta".');
} else {
if ('data' in doc && 'errors' in doc) {
errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document');
}
}
if ('data' in doc) {
if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) {
errors.push('data must be null, an object, or an array');
}
}
if ('meta' in doc) {
if (typeof doc.meta !== 'object') {
errors.push('meta must be an object');
}
}
if ('errors' in doc) {
if (!Array.isArray(doc.errors)) {
errors.push('errors must be an array');
}
}
if ('links' in doc) {
if (typeof doc.links !== 'object') {
errors.push('links must be an object');
}
}
if ('jsonapi' in doc) {
if (typeof doc.jsonapi !== 'object') {
errors.push('jsonapi must be an object');
}
}
if ('included' in doc) {
if (typeof doc.included !== 'object') {
errors.push('included must be an array');
}
}
}
return errors;
}
/*
This is a helper method that always returns a JSON-API Document.
@method normalizeResponseHelper
@param {DS.Serializer} serializer
@param {DS.Store} store
@param {subclass of DS.Model} modelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) {
var normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType);
var validationErrors = [];
if (false) {
validationErrors = validateDocumentStructure(normalizedResponse);
}
(false && _ember.default.assert('normalizeResponse must return a valid JSON API document:\n\t* ' + validationErrors.join('\n\t* '), _ember.default.isEmpty(validationErrors)));
return normalizedResponse;
}
});
define("ember-data/-private/system/store/serializers", ["exports"], function (exports) {
"use strict";
exports.__esModule = true;
exports.serializerForAdapter = serializerForAdapter;
function serializerForAdapter(store, adapter, modelName) {
var serializer = adapter.serializer;
if (serializer === undefined) {
serializer = store.serializerFor(modelName);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function (store, type, payload) {
return payload;
}
};
}
return serializer;
}
});
define('ember-data/-private/utils', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.getOwner = exports.modelHasAttributeOrRelationshipNamedType = undefined;
var get = _ember.default.get;
/*
Check if the passed model has a `type` attribute or a relationship named `type`.
@method modelHasAttributeOrRelationshipNamedType
@param modelClass
*/
function modelHasAttributeOrRelationshipNamedType(modelClass) {
return get(modelClass, 'attributes').has('type') || get(modelClass, 'relationshipsByName').has('type');
}
/*
ember-container-inject-owner is a new feature in Ember 2.3 that finally provides a public
API for looking items up. This function serves as a super simple polyfill to avoid
triggering deprecations.
*/
function getOwner(context) {
var owner = void 0;
if (_ember.default.getOwner) {
owner = _ember.default.getOwner(context);
} else if (context.container) {
owner = context.container;
}
if (owner && owner.lookupFactory && !owner._lookupFactory) {
// `owner` is a container, we are just making this work
owner._lookupFactory = owner.lookupFactory;
owner.register = function () {
var registry = owner.registry || owner._registry || owner;
return registry.register.apply(registry, arguments);
};
}
return owner;
}
exports.modelHasAttributeOrRelationshipNamedType = modelHasAttributeOrRelationshipNamedType;
exports.getOwner = getOwner;
});
define('ember-data/-private/utils/parse-response-headers', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = parseResponseHeaders;
var CLRF = '\u000d\u000a';
function parseResponseHeaders(headersString) {
var headers = Object.create(null);
if (!headersString) {
return headers;
}
var headerPairs = headersString.split(CLRF);
for (var i = 0; i < headerPairs.length; i++) {
var header = headerPairs[i];
var j = 0;
var foundSep = false;
for (; j < header.length; j++) {
if (header.charCodeAt(j) === 58 /* ':' */) {
foundSep = true;
break;
}
}
if (foundSep === false) {
break;
}
var field = header.substring(0, j).trim();
var value = header.substring(j + 1, header.length).trim();
if (value) {
headers[field] = value;
}
}
return headers;
}
});
define('ember-data/adapter', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = _ember.default.Object.extend({
/**
If you would like your adapter to use a custom serializer you can
set the `defaultSerializer` property to be the name of the custom
serializer.
Note the `defaultSerializer` serializer has a lower priority than
a model specific serializer (i.e. `PostSerializer`) or the
`application` serializer.
```app/adapters/django.js
import DS from 'ember-data';
export default DS.Adapter.extend({
defaultSerializer: 'django'
});
```
@property defaultSerializer
@type {String}
*/
defaultSerializer: '-default',
/**
The `findRecord()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `findRecord()` being called, you
should query your persistence layer for a record with the given ID. The `findRecord`
method should return a promise that will resolve to a JavaScript object that will be
normalized by the serializer.
Here is an example `findRecord` implementation:
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend({
findRecord(store, type, id, snapshot) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.getJSON(`/${type.modelName}/${id}`).then(function(data) {
resolve(data);
}, function(jqXHR) {
reject(jqXHR);
});
});
}
});
```
@method findRecord
@param {DS.Store} store
@param {DS.Model} type
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
findRecord: null,
/**
The `findAll()` method is used to retrieve all records for a given type.
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend({
findAll(store, type, sinceToken) {
let query = { since: sinceToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) {
resolve(data);
}, function(jqXHR) {
reject(jqXHR);
});
});
}
});
```
@method findAll
@param {DS.Store} store
@param {DS.Model} type
@param {String} sinceToken
@param {DS.SnapshotRecordArray} snapshotRecordArray
@return {Promise} promise
*/
findAll: null,
/**
This method is called when you call `query` on the store.
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend({
query(store, type, query) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) {
resolve(data);
}, function(jqXHR) {
reject(jqXHR);
});
});
}
});
```
@method query
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
query: null,
/**
The `queryRecord()` method is invoked when the store is asked for a single
record through a query object.
In response to `queryRecord()` being called, you should always fetch fresh
data. Once found, you can asynchronously call the store's `push()` method
to push the record into the store.
Here is an example `queryRecord` implementation:
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend(DS.BuildURLMixin, {
queryRecord(store, type, query) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) {
resolve(data);
}, function(jqXHR) {
reject(jqXHR);
});
});
}
});
```
@method queryRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@return {Promise} promise
*/
queryRecord: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
import DS from 'ember-data';
import { v4 } from 'uuid';
export default DS.Adapter.extend({
generateIdForRecord(store, inputProperties) {
return v4();
}
});
```
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {(String|Number)} id
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
createRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let url = `/${type.modelName}`;
// ...
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} serialized snapshot
*/
serialize: function (snapshot, options) {
return snapshot.serialize(options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and sends it to the server.
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend({
createRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
type: 'POST',
url: `/${type.modelName}`,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method createRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: null,
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and sends it to the server.
The updateRecord method is expected to return a promise that will
resolve with the serialized record. This allows the backend to
inform the Ember Data store the current state of this record after
the update. If it is not possible to return a serialized record
the updateRecord promise can also resolve with `undefined` and the
Ember Data store will assume all of the updates were successfully
applied on the backend.
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend({
updateRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let id = snapshot.id;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
type: 'PUT',
url: `/${type.modelName}/${id}`,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method updateRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: null,
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend({
deleteRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let id = snapshot.id;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
type: 'DELETE',
url: `/${type.modelName}/${id}`,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: null,
/**
By default the store will try to coalesce all `fetchRecord` calls within the same runloop
into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call.
You can opt out of this behaviour by either not implementing the findMany hook or by setting
coalesceFindRequests to false.
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: true,
/**
The store will call `findMany` instead of multiple `findRecord`
requests to find multiple records at once if coalesceFindRequests
is true.
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Adapter.extend({
findMany(store, type, ids, snapshots) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
type: 'GET',
url: `/${type.modelName}/`,
dataType: 'json',
data: { filter: { id: ids.join(',') } }
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method findMany
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the records
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany: null,
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
For example, if your api has nested URLs that depend on the parent, you will
want to group records by their parent.
The default implementation returns the records as a single group.
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} snapshots
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, snapshots) {
return [snapshots];
},
/**
This method is used by the store to determine if the store should
reload a record from the adapter when a record is requested by
`store.findRecord`.
If this method returns `true`, the store will re-fetch a record from
the adapter. If this method returns `false`, the store will resolve
immediately using the cached record.
For example, if you are building an events ticketing system, in which users
can only reserve tickets for 20 minutes at a time, and want to ensure that
in each route you have data that is no more than 20 minutes old you could
write:
```javascript
shouldReloadRecord(store, ticketSnapshot) {
let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt');
let timeDiff = moment().diff(lastAccessedAt, 'minutes');
if (timeDiff > 20) {
return true;
} else {
return false;
}
}
```
This method would ensure that whenever you do `store.findRecord('ticket',
id)` you will always get a ticket that is no more than 20 minutes old. In
case the cached version is more than 20 minutes old, `findRecord` will not
resolve until you fetched the latest version.
By default this hook returns `false`, as most UIs should not block user
interactions while waiting on data update.
Note that, with default settings, `shouldBackgroundReloadRecord` will always
re-fetch the records in the background even if `shouldReloadRecord` returns
`false`. You can override `shouldBackgroundReloadRecord` if this does not
suit your use case.
@since 1.13.0
@method shouldReloadRecord
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@return {Boolean}
*/
shouldReloadRecord: function (store, snapshot) {
return false;
},
/**
This method is used by the store to determine if the store should
reload all records from the adapter when records are requested by
`store.findAll`.
If this method returns `true`, the store will re-fetch all records from
the adapter. If this method returns `false`, the store will resolve
immediately using the cached records.
For example, if you are building an events ticketing system, in which users
can only reserve tickets for 20 minutes at a time, and want to ensure that
in each route you have data that is no more than 20 minutes old you could
write:
```javascript
shouldReloadAll(store, snapshotArray) {
let snapshots = snapshotArray.snapshots();
return snapshots.any((ticketSnapshot) => {
let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt');
let timeDiff = moment().diff(lastAccessedAt, 'minutes');
if (timeDiff > 20) {
return true;
} else {
return false;
}
});
}
```
This method would ensure that whenever you do `store.findAll('ticket')` you
will always get a list of tickets that are no more than 20 minutes old. In
case a cached version is more than 20 minutes old, `findAll` will not
resolve until you fetched the latest versions.
By default this methods returns `true` if the passed `snapshotRecordArray`
is empty (meaning that there are no records locally available yet),
otherwise it returns `false`.
Note that, with default settings, `shouldBackgroundReloadAll` will always
re-fetch all the records in the background even if `shouldReloadAll` returns
`false`. You can override `shouldBackgroundReloadAll` if this does not suit
your use case.
@since 1.13.0
@method shouldReloadAll
@param {DS.Store} store
@param {DS.SnapshotRecordArray} snapshotRecordArray
@return {Boolean}
*/
shouldReloadAll: function (store, snapshotRecordArray) {
return !snapshotRecordArray.length;
},
/**
This method is used by the store to determine if the store should
reload a record after the `store.findRecord` method resolves a
cached record.
This method is *only* checked by the store when the store is
returning a cached record.
If this method returns `true` the store will re-fetch a record from
the adapter.
For example, if you do not want to fetch complex data over a mobile
connection, or if the network is down, you can implement
`shouldBackgroundReloadRecord` as follows:
```javascript
shouldBackgroundReloadRecord(store, snapshot) {
let connection = window.navigator.connection;
if (connection === 'cellular' || connection === 'none') {
return false;
} else {
return true;
}
}
```
By default this hook returns `true` so the data for the record is updated
in the background.
@since 1.13.0
@method shouldBackgroundReloadRecord
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@return {Boolean}
*/
shouldBackgroundReloadRecord: function (store, snapshot) {
return true;
},
/**
This method is used by the store to determine if the store should
reload a record array after the `store.findAll` method resolves
with a cached record array.
This method is *only* checked by the store when the store is
returning a cached record array.
If this method returns `true` the store will re-fetch all records
from the adapter.
For example, if you do not want to fetch complex data over a mobile
connection, or if the network is down, you can implement
`shouldBackgroundReloadAll` as follows:
```javascript
shouldBackgroundReloadAll(store, snapshotArray) {
let connection = window.navigator.connection;
if (connection === 'cellular' || connection === 'none') {
return false;
} else {
return true;
}
}
```
By default this method returns `true`, indicating that a background reload
should always be triggered.
@since 1.13.0
@method shouldBackgroundReloadAll
@param {DS.Store} store
@param {DS.SnapshotRecordArray} snapshotRecordArray
@return {Boolean}
*/
shouldBackgroundReloadAll: function (store, snapshotRecordArray) {
return true;
}
});
});
define('ember-data/adapters/errors', ['exports', 'ember-data/-private'], function (exports, _private) {
'use strict';
exports.__esModule = true;
Object.defineProperty(exports, 'AdapterError', {
enumerable: true,
get: function () {
return _private.AdapterError;
}
});
Object.defineProperty(exports, 'InvalidError', {
enumerable: true,
get: function () {
return _private.InvalidError;
}
});
Object.defineProperty(exports, 'UnauthorizedError', {
enumerable: true,
get: function () {
return _private.UnauthorizedError;
}
});
Object.defineProperty(exports, 'ForbiddenError', {
enumerable: true,
get: function () {
return _private.ForbiddenError;
}
});
Object.defineProperty(exports, 'NotFoundError', {
enumerable: true,
get: function () {
return _private.NotFoundError;
}
});
Object.defineProperty(exports, 'ConflictError', {
enumerable: true,
get: function () {
return _private.ConflictError;
}
});
Object.defineProperty(exports, 'ServerError', {
enumerable: true,
get: function () {
return _private.ServerError;
}
});
Object.defineProperty(exports, 'TimeoutError', {
enumerable: true,
get: function () {
return _private.TimeoutError;
}
});
Object.defineProperty(exports, 'AbortError', {
enumerable: true,
get: function () {
return _private.AbortError;
}
});
Object.defineProperty(exports, 'errorsHashToArray', {
enumerable: true,
get: function () {
return _private.errorsHashToArray;
}
});
Object.defineProperty(exports, 'errorsArrayToHash', {
enumerable: true,
get: function () {
return _private.errorsArrayToHash;
}
});
});
define('ember-data/adapters/json-api', ['exports', 'ember', 'ember-data/adapters/rest', 'ember-data/-private', 'ember-data/-debug'], function (exports, _ember, _rest, _private, _debug) {
'use strict';
exports.__esModule = true;
/**
The `JSONAPIAdapter` is the default adapter used by Ember Data. It
is responsible for transforming the store's requests into HTTP
requests that follow the [JSON API](http://jsonapi.org/format/)
format.
## JSON API Conventions
The JSONAPIAdapter uses JSON API conventions for building the url
for a record and selecting the HTTP verb to use with a request. The
actions you can take on a record map onto the following URLs in the
JSON API adapter:
<table>
<tr>
<th>
Action
</th>
<th>
HTTP Verb
</th>
<th>
URL
</th>
</tr>
<tr>
<th>
`store.findRecord('post', 123)`
</th>
<td>
GET
</td>
<td>
/posts/123
</td>
</tr>
<tr>
<th>
`store.findAll('post')`
</th>
<td>
GET
</td>
<td>
/posts
</td>
</tr>
<tr>
<th>
Update `postRecord.save()`
</th>
<td>
PATCH
</td>
<td>
/posts/123
</td>
</tr>
<tr>
<th>
Create `store.createRecord('post').save()`
</th>
<td>
POST
</td>
<td>
/posts
</td>
</tr>
<tr>
<th>
Delete `postRecord.destroyRecord()`
</th>
<td>
DELETE
</td>
<td>
/posts/123
</td>
</tr>
</table>
## Success and failure
The JSONAPIAdapter will consider a success any response with a
status code of the 2xx family ("Success"), as well as 304 ("Not
Modified"). Any other status code will be considered a failure.
On success, the request promise will be resolved with the full
response payload.
Failed responses with status code 422 ("Unprocessable Entity") will
be considered "invalid". The response will be discarded, except for
the `errors` key. The request promise will be rejected with a
`DS.InvalidError`. This error object will encapsulate the saved
`errors` value.
Any other status codes will be treated as an adapter error. The
request promise will be rejected, similarly to the invalid case,
but with an instance of `DS.AdapterError` instead.
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the
namespace property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
namespace: 'api/1'
});
```
Requests for the `person` model would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
host: 'https://api.example.com'
});
```
Requests for the `person` model would now target
`https://api.example.com/people/1`.
@since 1.13.0
@class JSONAPIAdapter
@constructor
@namespace DS
@extends DS.RESTAdapter
*/
/* global heimdall */
/**
@module ember-data
*/
var JSONAPIAdapter = _rest.default.extend({
defaultSerializer: '-json-api',
ajaxOptions: function (url, type, options) {
var hash = this._super.apply(this, arguments);
if (hash.contentType) {
hash.contentType = 'application/vnd.api+json';
}
var beforeSend = hash.beforeSend;
hash.beforeSend = function (xhr) {
xhr.setRequestHeader('Accept', 'application/vnd.api+json');
if (beforeSend) {
beforeSend(xhr);
}
};
return hash;
},
/**
By default the JSONAPIAdapter will send each find request coming from a `store.find`
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of:
```javascript
{
data: {
id: 1,
type: 'post',
relationship: {
comments: {
data: [
{ id: 1, type: 'comment' },
{ id: 2, type: 'comment' }
]
}
}
}
}
```
By default calling `post.get('comments')` will trigger the following requests(assuming the
comments haven't been loaded before):
```
GET /comments/1
GET /comments/2
```
If you set coalesceFindRequests to `true` it will instead trigger the following request:
```
GET /comments?filter[id]=1,2
```
Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo`
relationships accessed within the same runloop. If you set `coalesceFindRequests: true`
```javascript
store.findRecord('comment', 1);
store.findRecord('comment', 2);
```
will also send a request to: `GET /comments?filter[id]=1,2`
Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app
`groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work.
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: false,
findMany: function (store, type, ids, snapshots) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
return this._super.apply(this, arguments);
} else {
var url = this.buildURL(type.modelName, ids, snapshots, 'findMany');
return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } });
}
},
pathForType: function (modelName) {
var dasherized = _ember.default.String.dasherize(modelName);
return _ember.default.String.pluralize(dasherized);
},
updateRecord: function (store, type, snapshot) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
return this._super.apply(this, arguments);
} else {
var data = {};
var serializer = store.serializerFor(type.modelName);
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
var url = this.buildURL(type.modelName, snapshot.id, snapshot, 'updateRecord');
return this.ajax(url, 'PATCH', { data: data });
}
},
_hasCustomizedAjax: function () {
if (this.ajax !== JSONAPIAdapter.prototype.ajax) {
(false && !(false) && _ember.default.deprecate('JSONAPIAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, {
id: 'ds.json-api-adapter.ajax',
until: '3.0.0'
}));
return true;
}
if (this.ajaxOptions !== JSONAPIAdapter.prototype.ajaxOptions) {
(false && !(false) && _ember.default.deprecate('JSONAPIAdapterr#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, {
id: 'ds.json-api-adapter.ajax-options',
until: '3.0.0'
}));
return true;
}
return false;
}
});
if ((0, _private.isEnabled)('ds-improved-ajax')) {
JSONAPIAdapter.reopen({
methodForRequest: function (params) {
if (params.requestType === 'updateRecord') {
return 'PATCH';
}
return this._super.apply(this, arguments);
},
dataForRequest: function (params) {
var requestType = params.requestType,
ids = params.ids;
if (requestType === 'findMany') {
return {
filter: { id: ids.join(',') }
};
}
if (requestType === 'updateRecord') {
var store = params.store,
type = params.type,
snapshot = params.snapshot;
var data = {};
var serializer = store.serializerFor(type.modelName);
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
return data;
}
return this._super.apply(this, arguments);
},
headersForRequest: function () {
var headers = this._super.apply(this, arguments) || {};
headers['Accept'] = 'application/vnd.api+json';
return headers;
},
_requestToJQueryAjaxHash: function () {
var hash = this._super.apply(this, arguments);
if (hash.contentType) {
hash.contentType = 'application/vnd.api+json';
}
return hash;
}
});
}
exports.default = JSONAPIAdapter;
});
define('ember-data/adapters/rest', ['exports', 'ember', 'ember-data/adapter', 'ember-data/-private', 'ember-data/-debug'], function (exports, _ember, _adapter, _private, _debug) {
'use strict';
exports.__esModule = true;
var MapWithDefault = _ember.default.MapWithDefault,
get = _ember.default.get;
var Promise = _ember.default.RSVP.Promise;
/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## Success and failure
The REST adapter will consider a success any response with a status code
of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other
status code will be considered a failure.
On success, the request promise will be resolved with the full response
payload.
Failed responses with status code 422 ("Unprocessable Entity") will be
considered "invalid". The response will be discarded, except for the
`errors` key. The request promise will be rejected with a `DS.InvalidError`.
This error object will encapsulate the saved `errors` value.
Any other status codes will be treated as an "adapter error". The request
promise will be rejected, similarly to the "invalid" case, but with
an instance of `DS.AdapterError` instead.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"posts": {
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
}
}
```
Similarly, in response to a `GET` request for `/posts`, the JSON should
look like this:
```js
{
"posts": [
{
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
},
{
"id": 2,
"title": "Rails is omakase",
"author": "D2H"
}
]
}
```
Note that the object root can be pluralized for both a single-object response
and an array response: the REST adapter is not strict on this. Further, if the
HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a
`findRecord` query) with more than one object in the array, Ember Data will
only display the object with the matching ID.
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"people": {
"id": 5,
"firstName": "Zaphod",
"lastName": "Beeblebrox",
"occupation": "President"
}
}
```
#### Relationships
Relationships are usually represented by ids to the record in the
relationship. The related records can then be sideloaded in the
response under a key for the type.
```js
{
"posts": {
"id": 5,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz",
"comments": [1, 2]
},
"comments": [{
"id": 1,
"author": "User 1",
"message": "First!",
}, {
"id": 2,
"author": "User 2",
"message": "Good Luck!",
}]
}
```
If the records in the relationship are not known when the response
is serialized its also possible to represent the relationship as a
url using the `links` key in the response. Ember Data will fetch
this url to resolve the relationship when it is accessed for the
first time.
```js
{
"posts": {
"id": 5,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz",
"links": {
"comments": "/posts/5/comments"
}
}
}
```
### Errors
If a response is considered a failure, the JSON payload is expected to include
a top-level key `errors`, detailing any specific issues. For example:
```js
{
"errors": {
"msg": "Something went wrong"
}
}
```
This adapter does not make any assumptions as to the format of the `errors`
object. It will simply be passed along as is, wrapped in an instance
of `DS.InvalidError` or `DS.AdapterError`. The serializer can interpret it
afterwards.
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
```
Requests for the `Person` model would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary
headers can be set as key/value pairs on the `RESTAdapter`'s `headers`
object and Ember Data will send them along with each ajax request.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
'API_KEY': 'secret key',
'ANOTHER_HEADER': 'Some header value'
}
});
```
`headers` can also be used as a computed property to support dynamic
headers. In the example below, the `session` object has been
injected into an adapter by Ember's container.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: Ember.computed('session.authToken', function() {
return {
'API_KEY': this.get('session.authToken'),
'ANOTHER_HEADER': 'Some header value'
};
})
});
```
In some cases, your dynamic headers may require data from some
object outside of Ember's observer system (for example
`document.cookie`). You can use the
[volatile](/api/classes/Ember.ComputedProperty.html#method_volatile)
function to set the property into a non-cached mode causing the headers to
be recomputed with every request.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: Ember.computed(function() {
return {
'API_KEY': Ember.get(document.cookie.match(/apiKey\=([^;]*)/), '1'),
'ANOTHER_HEADER': 'Some header value'
};
}).volatile()
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
@uses DS.BuildURLMixin
*/
var RESTAdapter = _adapter.default.extend(_private.BuildURLMixin, {
defaultSerializer: '-rest',
sortQueryParams: function (obj) {
var keys = Object.keys(obj);
var len = keys.length;
if (len < 2) {
return obj;
}
var newQueryParams = {};
var sortedKeys = keys.sort();
for (var i = 0; i < len; i++) {
newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]];
}
return newQueryParams;
},
/**
By default the RESTAdapter will send each find request coming from a `store.find`
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of:
```javascript
{
post: {
id: 1,
comments: [1, 2]
}
}
```
By default calling `post.get('comments')` will trigger the following requests(assuming the
comments haven't been loaded before):
```
GET /comments/1
GET /comments/2
```
If you set coalesceFindRequests to `true` it will instead trigger the following request:
```
GET /comments?ids[]=1&ids[]=2
```
Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo`
relationships accessed within the same runloop. If you set `coalesceFindRequests: true`
```javascript
store.findRecord('comment', 1);
store.findRecord('comment', 2);
```
will also send a request to: `GET /comments?ids[]=1&ids[]=2`
Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app
`groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work.
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: false,
findRecord: function (store, type, id, snapshot) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, id: id, snapshot: snapshot,
requestType: 'findRecord'
});
return this._makeRequest(request);
} else {
var url = this.buildURL(type.modelName, id, snapshot, 'findRecord');
var query = this.buildQuery(snapshot);
return this.ajax(url, 'GET', { data: query });
}
},
findAll: function (store, type, sinceToken, snapshotRecordArray) {
var query = this.buildQuery(snapshotRecordArray);
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, sinceToken: sinceToken, query: query,
snapshots: snapshotRecordArray,
requestType: 'findAll'
});
return this._makeRequest(request);
} else {
var url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll');
if (sinceToken) {
query.since = sinceToken;
}
return this.ajax(url, 'GET', { data: query });
}
},
query: function (store, type, query) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, query: query,
requestType: 'query'
});
return this._makeRequest(request);
} else {
var url = this.buildURL(type.modelName, null, null, 'query', query);
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
return this.ajax(url, 'GET', { data: query });
}
},
queryRecord: function (store, type, query) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, query: query,
requestType: 'queryRecord'
});
return this._makeRequest(request);
} else {
var url = this.buildURL(type.modelName, null, null, 'queryRecord', query);
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
return this.ajax(url, 'GET', { data: query });
}
},
findMany: function (store, type, ids, snapshots) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, ids: ids, snapshots: snapshots,
requestType: 'findMany'
});
return this._makeRequest(request);
} else {
var url = this.buildURL(type.modelName, ids, snapshots, 'findMany');
return this.ajax(url, 'GET', { data: { ids: ids } });
}
},
findHasMany: function (store, snapshot, url, relationship) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, snapshot: snapshot, url: url, relationship: relationship,
requestType: 'findHasMany'
});
return this._makeRequest(request);
} else {
var id = snapshot.id;
var type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany'));
return this.ajax(url, 'GET');
}
},
findBelongsTo: function (store, snapshot, url, relationship) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, snapshot: snapshot, url: url, relationship: relationship,
requestType: 'findBelongsTo'
});
return this._makeRequest(request);
} else {
var id = snapshot.id;
var type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo'));
return this.ajax(url, 'GET');
}
},
createRecord: function (store, type, snapshot) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, snapshot: snapshot,
requestType: 'createRecord'
});
return this._makeRequest(request);
} else {
var data = {};
var serializer = store.serializerFor(type.modelName);
var url = this.buildURL(type.modelName, null, snapshot, 'createRecord');
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
return this.ajax(url, "POST", { data: data });
}
},
updateRecord: function (store, type, snapshot) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, snapshot: snapshot,
requestType: 'updateRecord'
});
return this._makeRequest(request);
} else {
var data = {};
var serializer = store.serializerFor(type.modelName);
serializer.serializeIntoHash(data, type, snapshot);
var id = snapshot.id;
var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord');
return this.ajax(url, "PUT", { data: data });
}
},
deleteRecord: function (store, type, snapshot) {
if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) {
var request = this._requestFor({
store: store, type: type, snapshot: snapshot,
requestType: 'deleteRecord'
});
return this._makeRequest(request);
} else {
var id = snapshot.id;
return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE");
}
},
_stripIDFromURL: function (store, snapshot) {
var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot);
var expandedURL = url.split('/');
// Case when the url is of the format ...something/:id
// We are decodeURIComponent-ing the lastSegment because if it represents
// the id, it has been encodeURIComponent-ified within `buildURL`. If we
// don't do this, then records with id having special characters are not
// coalesced correctly (see GH #4190 for the reported bug)
var lastSegment = expandedURL[expandedURL.length - 1];
var id = snapshot.id;
if (decodeURIComponent(lastSegment) === id) {
expandedURL[expandedURL.length - 1] = "";
} else if (endsWith(lastSegment, '?id=' + id)) {
//Case when the url is of the format ...something?id=:id
expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1);
}
return expandedURL.join('/');
},
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
maxURLLength: 2048,
groupRecordsForFindMany: function (store, snapshots) {
var groups = MapWithDefault.create({
defaultValue: function () {
return [];
}
});
var adapter = this;
var maxURLLength = this.maxURLLength;
snapshots.forEach(function (snapshot) {
var baseUrl = adapter._stripIDFromURL(store, snapshot);
groups.get(baseUrl).push(snapshot);
});
function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) {
var idsSize = 0;
var baseUrl = adapter._stripIDFromURL(store, group[0]);
var splitGroups = [[]];
group.forEach(function (snapshot) {
var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength;
if (baseUrl.length + idsSize + additionalLength >= maxURLLength) {
idsSize = 0;
splitGroups.push([]);
}
idsSize += additionalLength;
var lastGroupIndex = splitGroups.length - 1;
splitGroups[lastGroupIndex].push(snapshot);
});
return splitGroups;
}
var groupsArray = [];
groups.forEach(function (group, key) {
var paramNameLength = '&ids%5B%5D='.length;
var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength);
splitGroups.forEach(function (splitGroup) {
return groupsArray.push(splitGroup);
});
});
return groupsArray;
},
handleResponse: function (status, headers, payload, requestData) {
if (this.isSuccess(status, headers, payload)) {
return payload;
} else if (this.isInvalid(status, headers, payload)) {
return new _private.InvalidError(payload.errors);
}
var errors = this.normalizeErrorResponse(status, headers, payload);
var detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData);
if ((0, _private.isEnabled)('ds-extended-errors')) {
switch (status) {
case 401:
return new _private.UnauthorizedError(errors, detailedMessage);
case 403:
return new _private.ForbiddenError(errors, detailedMessage);
case 404:
return new _private.NotFoundError(errors, detailedMessage);
case 409:
return new _private.ConflictError(errors, detailedMessage);
default:
if (status >= 500) {
return new _private.ServerError(errors, detailedMessage);
}
}
}
return new _private.AdapterError(errors, detailedMessage);
},
isSuccess: function (status, headers, payload) {
return status >= 200 && status < 300 || status === 304;
},
isInvalid: function (status, headers, payload) {
return status === 422;
},
ajax: function (url, type, options) {
var adapter = this;
var requestData = {
url: url,
method: type
};
return new Promise(function (resolve, reject) {
var hash = adapter.ajaxOptions(url, type, options);
hash.success = function (payload, textStatus, jqXHR) {
var response = ajaxSuccess(adapter, jqXHR, payload, requestData);
_ember.default.run.join(null, resolve, response);
};
hash.error = function (jqXHR, textStatus, errorThrown) {
var responseData = {
textStatus: textStatus,
errorThrown: errorThrown
};
var error = ajaxError(adapter, jqXHR, requestData, responseData);
_ember.default.run.join(null, reject, error);
};
adapter._ajaxRequest(hash);
}, 'DS: RESTAdapter#ajax ' + type + ' to ' + url);
},
_ajaxRequest: function (options) {
_ember.default.$.ajax(options);
},
ajaxOptions: function (url, type, options) {
var hash = options || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
var headers = get(this, 'headers');
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
Object.keys(headers).forEach(function (key) {
return xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
},
parseErrorResponse: function (responseText) {
var json = responseText;
try {
json = _ember.default.$.parseJSON(responseText);
} catch (e) {
// ignored
}
return json;
},
normalizeErrorResponse: function (status, headers, payload) {
if (payload && typeof payload === 'object' && payload.errors) {
return payload.errors;
} else {
return [{
status: '' + status,
title: "The backend responded with an error",
detail: '' + payload
}];
}
},
/**
Generates a detailed ("friendly") error message, with plenty
of information for debugging (good luck!)
@method generatedDetailedMessage
@private
@param {Number} status
@param {Object} headers
@param {Object} payload
@param {Object} requestData
@return {String} detailed error message
*/
generatedDetailedMessage: function (status, headers, payload, requestData) {
var shortenedPayload = void 0;
var payloadContentType = headers["Content-Type"] || "Empty Content-Type";
if (payloadContentType === "text/html" && payload.length > 250) {
shortenedPayload = "[Omitted Lengthy HTML]";
} else {
shortenedPayload = payload;
}
var requestDescription = requestData.method + ' ' + requestData.url;
var payloadDescription = 'Payload (' + payloadContentType + ')';
return ['Ember Data Request ' + requestDescription + ' returned a ' + status, payloadDescription, shortenedPayload].join('\n');
},
buildQuery: function (snapshot) {
var query = {};
if (snapshot) {
var include = snapshot.include;
if (include) {
query.include = include;
}
}
return query;
},
_hasCustomizedAjax: function () {
if (this.ajax !== RESTAdapter.prototype.ajax) {
(false && !(false) && _ember.default.deprecate('RESTAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, {
id: 'ds.rest-adapter.ajax',
until: '3.0.0'
}));
return true;
}
if (this.ajaxOptions !== RESTAdapter.prototype.ajaxOptions) {
(false && !(false) && _ember.default.deprecate('RESTAdapter#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, {
id: 'ds.rest-adapter.ajax-options',
until: '3.0.0'
}));
return true;
}
return false;
}
});
if ((0, _private.isEnabled)('ds-improved-ajax')) {
RESTAdapter.reopen({
dataForRequest: function (params) {
var store = params.store,
type = params.type,
snapshot = params.snapshot,
requestType = params.requestType,
query = params.query;
// type is not passed to findBelongsTo and findHasMany
type = type || snapshot && snapshot.type;
var serializer = store.serializerFor(type.modelName);
var data = {};
switch (requestType) {
case 'createRecord':
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
break;
case 'updateRecord':
serializer.serializeIntoHash(data, type, snapshot);
break;
case 'findRecord':
data = this.buildQuery(snapshot);
break;
case 'findAll':
if (params.sinceToken) {
query = query || {};
query.since = params.sinceToken;
}
data = query;
break;
case 'query':
case 'queryRecord':
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
data = query;
break;
case 'findMany':
data = { ids: params.ids };
break;
default:
data = undefined;
break;
}
return data;
},
methodForRequest: function (params) {
var requestType = params.requestType;
switch (requestType) {
case 'createRecord':
return 'POST';
case 'updateRecord':
return 'PUT';
case 'deleteRecord':
return 'DELETE';
}
return 'GET';
},
urlForRequest: function (params) {
var type = params.type,
id = params.id,
ids = params.ids,
snapshot = params.snapshot,
snapshots = params.snapshots,
requestType = params.requestType,
query = params.query;
// type and id are not passed from updateRecord and deleteRecord, hence they
// are defined if not set
type = type || snapshot && snapshot.type;
id = id || snapshot && snapshot.id;
switch (requestType) {
case 'findAll':
return this.buildURL(type.modelName, null, snapshots, requestType);
case 'query':
case 'queryRecord':
return this.buildURL(type.modelName, null, null, requestType, query);
case 'findMany':
return this.buildURL(type.modelName, ids, snapshots, requestType);
case 'findHasMany':
case 'findBelongsTo':
{
var url = this.buildURL(type.modelName, id, snapshot, requestType);
return this.urlPrefix(params.url, url);
}
}
return this.buildURL(type.modelName, id, snapshot, requestType, query);
},
headersForRequest: function (params) {
return this.get('headers');
},
_requestFor: function (params) {
var method = this.methodForRequest(params);
var url = this.urlForRequest(params);
var headers = this.headersForRequest(params);
var data = this.dataForRequest(params);
return { method: method, url: url, headers: headers, data: data };
},
_requestToJQueryAjaxHash: function (request) {
var hash = {};
hash.type = request.method;
hash.url = request.url;
hash.dataType = 'json';
hash.context = this;
if (request.data) {
if (request.method !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(request.data);
} else {
hash.data = request.data;
}
}
var headers = request.headers;
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
Object.keys(headers).forEach(function (key) {
return xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
},
_makeRequest: function (request) {
var adapter = this;
var hash = this._requestToJQueryAjaxHash(request);
var method = request.method,
url = request.url;
var requestData = { method: method, url: url };
return new _ember.default.RSVP.Promise(function (resolve, reject) {
hash.success = function (payload, textStatus, jqXHR) {
var response = ajaxSuccess(adapter, jqXHR, payload, requestData);
_ember.default.run.join(null, resolve, response);
};
hash.error = function (jqXHR, textStatus, errorThrown) {
var responseData = {
textStatus: textStatus,
errorThrown: errorThrown
};
var error = ajaxError(adapter, jqXHR, requestData, responseData);
_ember.default.run.join(null, reject, error);
};
adapter._ajaxRequest(hash);
}, 'DS: RESTAdapter#makeRequest: ' + method + ' ' + url);
}
});
}
function ajaxSuccess(adapter, jqXHR, payload, requestData) {
var response = void 0;
try {
response = adapter.handleResponse(jqXHR.status, (0, _private.parseResponseHeaders)(jqXHR.getAllResponseHeaders()), payload, requestData);
} catch (error) {
return Promise.reject(error);
}
if (response && response.isAdapterError) {
return Promise.reject(response);
} else {
return response;
}
}
function ajaxError(adapter, jqXHR, requestData, responseData) {
if (false) {
var message = 'The server returned an empty string for ' + requestData.method + ' ' + requestData.url + ', which cannot be parsed into a valid JSON. Return either null or {}.';
var validJSONString = !(responseData.textStatus === "parsererror" && jqXHR.responseText === "");
(false && _ember.default.warn(message, validJSONString, {
id: 'ds.adapter.returned-empty-string-as-JSON'
}));
}
var error = void 0;
if (responseData.errorThrown instanceof Error) {
error = responseData.errorThrown;
} else if (responseData.textStatus === 'timeout') {
error = new _private.TimeoutError();
} else if (responseData.textStatus === 'abort' || jqXHR.status === 0) {
error = new _private.AbortError();
} else {
try {
error = adapter.handleResponse(jqXHR.status, (0, _private.parseResponseHeaders)(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || responseData.errorThrown, requestData);
} catch (e) {
error = e;
}
}
return error;
}
//From http://stackoverflow.com/questions/280634/endswith-in-javascript
function endsWith(string, suffix) {
if (typeof String.prototype.endsWith !== 'function') {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
} else {
return string.endsWith(suffix);
}
}
exports.default = RESTAdapter;
});
define('ember-data/attr', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = attr;
/**
@module ember-data
*/
function getDefaultValue(record, options, key) {
if (typeof options.defaultValue === 'function') {
return options.defaultValue.apply(null, arguments);
} else {
var defaultValue = options.defaultValue;
(false && !(typeof defaultValue !== 'object' || defaultValue === null) && _ember.default.deprecate('Non primitive defaultValues are deprecated because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.', typeof defaultValue !== 'object' || defaultValue === null, {
id: 'ds.defaultValue.complex-object',
until: '3.0.0'
}));
return defaultValue;
}
}
function hasValue(record, key) {
return key in record._attributes || key in record._inFlightAttributes || key in record._data;
}
function getValue(record, key) {
if (key in record._attributes) {
return record._attributes[key];
} else if (key in record._inFlightAttributes) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](/api/data/classes/DS.Transform.html).
Note that you cannot use `attr` to define an attribute of `id`.
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
verified: DS.attr('boolean', { defaultValue: false })
});
```
Default value can also be a function. This is useful it you want to return
a new object for each attribute.
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
settings: DS.attr({
defaultValue() {
return {};
}
})
});
```
The `options` hash is passed as second argument to a transforms'
`serialize` and `deserialize` method. This allows to configure a
transformation and adapt the corresponding value, based on the config:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
text: DS.attr('text', {
uppercase: true
})
});
```
```app/transforms/text.js
import DS from 'ember-data';
export default DS.Transform.extend({
serialize(value, options) {
if (options.uppercase) {
return value.toUpperCase();
}
return value;
},
deserialize(value) {
return value;
}
})
```
@namespace
@method attr
@for DS
@param {String|Object} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
function attr(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
} else {
options = options || {};
}
var meta = {
type: type,
isAttribute: true,
options: options
};
return _ember.default.computed({
get: function (key) {
var internalModel = this._internalModel;
if (hasValue(internalModel, key)) {
return getValue(internalModel, key);
} else {
return getDefaultValue(this, options, key);
}
},
set: function (key, value) {
var internalModel = this._internalModel;
var oldValue = getValue(internalModel, key);
var originalValue = void 0;
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
internalModel._attributes[key] = value;
if (key in internalModel._inFlightAttributes) {
originalValue = internalModel._inFlightAttributes[key];
} else {
originalValue = internalModel._data[key];
}
this._internalModel.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: originalValue,
value: value
});
}
return value;
}
}).meta(meta);
}
});
define("ember-data", ["exports", "ember", "ember-data/-private", "ember-data/setup-container", "ember-data/instance-initializers/initialize-store-service", "ember-data/transforms/transform", "ember-data/transforms/number", "ember-data/transforms/date", "ember-data/transforms/string", "ember-data/transforms/boolean", "ember-data/adapter", "ember-data/adapters/json-api", "ember-data/adapters/rest", "ember-data/serializer", "ember-data/serializers/json-api", "ember-data/serializers/json", "ember-data/serializers/rest", "ember-data/serializers/embedded-records-mixin", "ember-data/attr", "ember-inflector"], function (exports, _ember, _private, _setupContainer, _initializeStoreService, _transform, _number, _date, _string, _boolean, _adapter, _jsonApi, _rest, _serializer, _jsonApi2, _json, _rest2, _embeddedRecordsMixin, _attr) {
"use strict";
exports.__esModule = true;
/**
Ember Data
@module ember-data
@main ember-data
*/
if (_ember.default.VERSION.match(/^1\.([0-9]|1[0-2])\./)) {
throw new _ember.default.Error("Ember Data requires at least Ember 1.13.0, but you have " + _ember.default.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data.");
}
_private.DS.Store = _private.Store;
_private.DS.PromiseArray = _private.PromiseArray;
_private.DS.PromiseObject = _private.PromiseObject;
_private.DS.PromiseManyArray = _private.PromiseManyArray;
_private.DS.Model = _private.Model;
_private.DS.RootState = _private.RootState;
_private.DS.attr = _attr.default;
_private.DS.Errors = _private.Errors;
_private.DS.InternalModel = _private.InternalModel;
_private.DS.Snapshot = _private.Snapshot;
_private.DS.Adapter = _adapter.default;
_private.DS.AdapterError = _private.AdapterError;
_private.DS.InvalidError = _private.InvalidError;
_private.DS.TimeoutError = _private.TimeoutError;
_private.DS.AbortError = _private.AbortError;
if ((0, _private.isEnabled)('ds-extended-errors')) {
_private.DS.UnauthorizedError = _private.UnauthorizedError;
_private.DS.ForbiddenError = _private.ForbiddenError;
_private.DS.NotFoundError = _private.NotFoundError;
_private.DS.ConflictError = _private.ConflictError;
_private.DS.ServerError = _private.ServerError;
}
_private.DS.errorsHashToArray = _private.errorsHashToArray;
_private.DS.errorsArrayToHash = _private.errorsArrayToHash;
_private.DS.Serializer = _serializer.default;
_private.DS.DebugAdapter = _private.DebugAdapter;
_private.DS.RecordArray = _private.RecordArray;
_private.DS.FilteredRecordArray = _private.FilteredRecordArray;
_private.DS.AdapterPopulatedRecordArray = _private.AdapterPopulatedRecordArray;
_private.DS.ManyArray = _private.ManyArray;
_private.DS.RecordArrayManager = _private.RecordArrayManager;
_private.DS.RESTAdapter = _rest.default;
_private.DS.BuildURLMixin = _private.BuildURLMixin;
_private.DS.RESTSerializer = _rest2.default;
_private.DS.JSONSerializer = _json.default;
_private.DS.JSONAPIAdapter = _jsonApi.default;
_private.DS.JSONAPISerializer = _jsonApi2.default;
_private.DS.Transform = _transform.default;
_private.DS.DateTransform = _date.default;
_private.DS.StringTransform = _string.default;
_private.DS.NumberTransform = _number.default;
_private.DS.BooleanTransform = _boolean.default;
_private.DS.EmbeddedRecordsMixin = _embeddedRecordsMixin.default;
_private.DS.belongsTo = _private.belongsTo;
_private.DS.hasMany = _private.hasMany;
_private.DS.Relationship = _private.Relationship;
_private.DS._setupContainer = _setupContainer.default;
_private.DS._initializeStoreService = _initializeStoreService.default;
Object.defineProperty(_private.DS, 'normalizeModelName', {
enumerable: true,
writable: false,
configurable: false,
value: _private.normalizeModelName
});
Object.defineProperty(_private.global, 'DS', {
configurable: true,
get: function () {
(false && !(false) && _ember.default.deprecate('Using the global version of DS is deprecated. Please either import ' + 'the specific modules needed or `import DS from \'ember-data\';`.', false, { id: 'ember-data.global-ds', until: '3.0.0' }));
return _private.DS;
}
});
exports.default = _private.DS;
});
define('ember-data/initializers/data-adapter', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = {
name: 'data-adapter',
before: 'store',
initialize: function () {}
};
});
define('ember-data/initializers/ember-data', ['exports', 'ember-data/setup-container', 'ember-data/index'], function (exports, _setupContainer) {
'use strict';
exports.__esModule = true;
exports.default = {
name: 'ember-data',
initialize: _setupContainer.default
};
});
define('ember-data/initializers/injectStore', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = {
name: 'injectStore',
before: 'store',
initialize: function () {}
};
});
define('ember-data/initializers/store', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = {
name: 'store',
after: 'ember-data',
initialize: function () {}
};
});
define('ember-data/initializers/transforms', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = {
name: 'transforms',
before: 'store',
initialize: function () {}
};
});
define("ember-data/instance-initializers/ember-data", ["exports", "ember-data/instance-initializers/initialize-store-service"], function (exports, _initializeStoreService) {
"use strict";
exports.__esModule = true;
exports.default = {
name: "ember-data",
initialize: _initializeStoreService.default
};
});
define('ember-data/instance-initializers/initialize-store-service', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = initializeStoreService;
var deprecateOldEmberDataInitializers = void 0;
/*
Configures a registry for use with an Ember-Data
store.
@method initializeStoreService
@param {Ember.ApplicationInstance | Ember.EngineInstance} instance
*/
function initializeStoreService(instance) {
// instance.lookup supports Ember 2.1 and higher
// instance.container supports Ember 1.11 - 2.0
var container = instance.lookup ? instance : instance.container;
// Eagerly generate the store so defaultStore is populated.
container.lookup('service:store');
if (false) {
// In Ember 2.4+ instance.base is the `Ember.Application` or `Ember.Engine` instance
// In Ember 1.11 - 2.3 we fallback to `instance.application`
var base = instance.base || instance.application;
deprecateOldEmberDataInitializers(base.constructor.initializers);
}
}
if (false) {
var DEPRECATED_INITIALIZER_NAMES = ['data-adapter', 'injectStore', 'transforms', 'store'];
var matchesDeprecatedInititalizer = function matchesDeprecatedInititalizer(name) {
return DEPRECATED_INITIALIZER_NAMES.indexOf(name) !== -1;
};
var warnForDeprecatedInitializers = function warnForDeprecatedInitializers(initializer) {
var deprecatedBeforeInitializer = matchesDeprecatedInititalizer(initializer.before);
var deprecatedAfterInitializer = matchesDeprecatedInititalizer(initializer.after);
var deprecatedProp = deprecatedBeforeInitializer ? 'before' : 'after';
(false && !(!(deprecatedBeforeInitializer || deprecatedAfterInitializer)) && Ember.deprecate('The initializer `' + initializer[deprecatedProp] + '` has been deprecated. Please update your `' + initializer.name + '` initializer to use use `' + deprecatedProp + ': \'ember-data\'` instead.', !(deprecatedBeforeInitializer || deprecatedAfterInitializer), {
id: 'ds.deprecated-initializers',
until: '3.0.0'
}));
};
deprecateOldEmberDataInitializers = function deprecateOldEmberDataInitializers(initializers) {
// collect all of the initializers
var keys = Object.keys(initializers);
for (var i = 0; i < keys.length; i++) {
var name = keys[i];
// filter out all of the Ember Data initializer. We have some
// deprecated initializers that depend on other deprecated
// initializers which may trigger the deprecation warning
// unintentionally.
if (!matchesDeprecatedInititalizer(name)) {
warnForDeprecatedInitializers(initializers[name]);
}
}
};
}
});
define('ember-data/model', ['exports', 'ember-data/-private'], function (exports, _private) {
'use strict';
exports.__esModule = true;
Object.defineProperty(exports, 'default', {
enumerable: true,
get: function () {
return _private.Model;
}
});
});
define('ember-data/relationships', ['exports', 'ember-data/-private'], function (exports, _private) {
'use strict';
exports.__esModule = true;
Object.defineProperty(exports, 'belongsTo', {
enumerable: true,
get: function () {
return _private.belongsTo;
}
});
Object.defineProperty(exports, 'hasMany', {
enumerable: true,
get: function () {
return _private.hasMany;
}
});
});
define('ember-data/serializer', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = _ember.default.Object.extend({
/**
The `store` property is the application's `store` that contains
all records. It can be used to look up serializers for other model
types that may be nested inside the payload response.
Example:
```js
Serializer.extend({
extractRelationship(relationshipModelName, relationshipHash) {
var modelClass = this.store.modelFor(relationshipModelName);
var relationshipSerializer = this.store.serializerFor(relationshipModelName);
return relationshipSerializer.normalize(modelClass, relationshipHash);
}
});
```
@property store
@type {DS.Store}
@public
*/
/**
The `normalizeResponse` method is used to normalize a payload from the
server to a JSON-API Document.
http://jsonapi.org/format/#document-structure
Example:
```js
Serializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
if (requestType === 'findRecord') {
return this.normalize(primaryModelClass, payload);
} else {
return payload.reduce(function(documentHash, item) {
let { data, included } = this.normalize(primaryModelClass, item);
documentHash.included.push(...included);
documentHash.data.push(data);
return documentHash;
}, { data: [], included: [] })
}
}
});
```
@since 1.13.0
@method normalizeResponse
@param {DS.Store} store
@param {DS.Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeResponse: null,
/**
The `serialize` method is used when a record is saved in order to convert
the record into the form that your external data source expects.
`serialize` takes an optional `options` hash with a single option:
- `includeId`: If this is `true`, `serialize` should include the ID
in the serialized object it builds.
Example:
```js
Serializer.extend({
serialize(snapshot, options) {
var json = {
id: snapshot.id
};
snapshot.eachAttribute((key, attribute) => {
json[key] = snapshot.attr(key);
});
snapshot.eachRelationship((key, relationship) => {
if (relationship.kind === 'belongsTo') {
json[key] = snapshot.belongsTo(key, { id: true });
} else if (relationship.kind === 'hasMany') {
json[key] = snapshot.hasMany(key, { ids: true });
}
});
return json;
},
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} [options]
@return {Object}
*/
serialize: null,
/**
The `normalize` method is used to convert a payload received from your
external data source into the normalized form `store.push()` expects. You
should override this method, munge the hash and return the normalized
payload.
Example:
```js
Serializer.extend({
normalize(modelClass, resourceHash) {
var data = {
id: resourceHash.id,
type: modelClass.modelName,
attributes: resourceHash
};
return { data: data };
}
})
```
@method normalize
@param {DS.Model} typeClass
@param {Object} hash
@return {Object}
*/
normalize: function (typeClass, hash) {
return hash;
}
});
});
define('ember-data/serializers/embedded-records-mixin', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}
var get = _ember.default.get;
var set = _ember.default.set;
var camelize = _ember.default.String.camelize;
/**
## Using Embedded Records
`DS.EmbeddedRecordsMixin` supports serializing embedded records.
To set up embedded records, include the mixin when extending a serializer,
then define and configure embedded (model) relationships.
Note that embedded records will serialize with the serializer for their model instead of the serializer in which they are defined.
Below is an example of a per-type serializer (`post` type).
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: { embedded: 'always' },
comments: { serialize: 'ids' }
}
});
```
Note that this use of `{ embedded: 'always' }` is unrelated to
the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of
defining a model while working with the `ActiveModelSerializer`. Nevertheless,
using `{ embedded: 'always' }` as an option to `DS.attr` is not a valid way to setup
embedded records.
The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for:
```js
{
serialize: 'records',
deserialize: 'records'
}
```
### Configuring Attrs
A resource's `attrs` option may be set to use `ids`, `records` or false for the
`serialize` and `deserialize` settings.
The `attrs` property can be set on the `ApplicationSerializer` or a per-type
serializer.
In the case where embedded JSON is expected while extracting a payload (reading)
the setting is `deserialize: 'records'`, there is no need to use `ids` when
extracting as that is the default behavior without this mixin if you are using
the vanilla `EmbeddedRecordsMixin`. Likewise, to embed JSON in the payload while
serializing `serialize: 'records'` is the setting to use. There is an option of
not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
do not want the relationship sent at all, you can use `serialize: false`.
### EmbeddedRecordsMixin defaults
If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
will behave in the following way:
BelongsTo: `{ serialize: 'id', deserialize: 'id' }`
HasMany: `{ serialize: false, deserialize: 'ids' }`
### Model Relationships
Embedded records must have a model defined to be extracted and serialized. Note that
when defining any relationships on your model such as `belongsTo` and `hasMany`, you
should not both specify `async: true` and also indicate through the serializer's
`attrs` attribute that the related model should be embedded for deserialization.
If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`),
then do not use `async: true`.
To successfully extract and serialize embedded records the model relationships
must be setup correcty. See the
[defining relationships](/guides/models/defining-models/#toc_defining-relationships)
section of the **Defining Models** guide page.
Records without an `id` property are not considered embedded records, model
instances must have an `id` property to be used with Ember Data.
### Example JSON payloads, Models and Serializers
**When customizing a serializer it is important to grok what the customizations
are. Please read the docs for the methods this mixin provides, in case you need
to modify it to fit your specific needs.**
For example review the docs for each method of this mixin:
* [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize)
* [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo)
* [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany)
@class EmbeddedRecordsMixin
@namespace DS
*/
exports.default = _ember.default.Mixin.create({
/**
Normalize the record and recursively normalize/extract all the embedded records
while pushing them into the store as they are encountered
A payload with an attr configured for embedded records needs to be extracted:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
@method normalize
@param {DS.Model} typeClass
@param {Object} hash to be normalized
@param {String} prop the hash has been referenced by
@return {Object} the normalized hash
**/
normalize: function (typeClass, hash, prop) {
var normalizedHash = this._super(typeClass, hash, prop);
return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash);
},
keyForRelationship: function (key, typeClass, method) {
if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) {
return this.keyForAttribute(key, method);
} else {
return this._super(key, typeClass, method) || key;
}
},
/**
Serialize `belongsTo` relationship when it is configured as an embedded object.
This example of an author model belongs to a post model:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
author: DS.belongsTo('author')
});
Author = DS.Model.extend({
name: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded author
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: { embedded: 'always' }
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"author": {
"id": "2"
"name": "dhh"
}
}
}
```
@method serializeBelongsTo
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function (snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var embeddedSnapshot = snapshot.belongsTo(attr);
if (includeIds) {
var serializedKey = this._getMappedKey(relationship.key, snapshot.type);
if (serializedKey === relationship.key && this.keyForRelationship) {
serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize");
}
if (!embeddedSnapshot) {
json[serializedKey] = null;
} else {
json[serializedKey] = embeddedSnapshot.id;
if (relationship.options.polymorphic) {
this.serializePolymorphicType(snapshot, json, relationship);
}
}
} else if (includeRecords) {
this._serializeEmbeddedBelongsTo(snapshot, json, relationship);
}
},
_serializeEmbeddedBelongsTo: function (snapshot, json, relationship) {
var embeddedSnapshot = snapshot.belongsTo(relationship.key);
var serializedKey = this._getMappedKey(relationship.key, snapshot.type);
if (serializedKey === relationship.key && this.keyForRelationship) {
serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize");
}
if (!embeddedSnapshot) {
json[serializedKey] = null;
} else {
json[serializedKey] = embeddedSnapshot.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]);
if (relationship.options.polymorphic) {
this.serializePolymorphicType(snapshot, json, relationship);
}
}
},
/**
Serializes `hasMany` relationships when it is configured as embedded objects.
This example of a post model has many comments:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment')
});
Comment = DS.Model.extend({
body: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded comments
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: { embedded: 'always' }
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
The attrs options object can use more specific instruction for extracting and
serializing. When serializing, an option to embed `ids`, `ids-and-types` or `records` can be set.
When extracting the only option is `records`.
So `{ embedded: 'always' }` is shorthand for:
`{ serialize: 'records', deserialize: 'records' }`
To embed the `ids` for a related object (using a hasMany relationship):
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: { serialize: 'ids', deserialize: 'records' }
}
})
```
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": ["1", "2"]
}
}
```
To embed the relationship as a collection of objects with `id` and `type` keys, set
`ids-and-types` for the related object.
This is particularly useful for polymorphic relationships where records don't share
the same table and the `id` is not enough information.
By example having a user that has many pets:
```js
User = DS.Model.extend({
name: DS.attr('string'),
pets: DS.hasMany('pet', { polymorphic: true })
});
Pet = DS.Model.extend({
name: DS.attr('string'),
});
Cat = Pet.extend({
// ...
});
Parrot = Pet.extend({
// ...
});
```
```app/serializers/user.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
pets: { serialize: 'ids-and-types', deserialize: 'records' }
}
});
```
```js
{
"user": {
"id": "1"
"name": "Bertin Osborne",
"pets": [
{ "id": "1", "type": "Cat" },
{ "id": "1", "type": "Parrot"}
]
}
}
```
@method serializeHasMany
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function (snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
if (this.hasSerializeIdsOption(attr)) {
var serializedKey = this._getMappedKey(relationship.key, snapshot.type);
if (serializedKey === relationship.key && this.keyForRelationship) {
serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize");
}
json[serializedKey] = snapshot.hasMany(attr, { ids: true });
} else if (this.hasSerializeRecordsOption(attr)) {
this._serializeEmbeddedHasMany(snapshot, json, relationship);
} else {
if (this.hasSerializeIdsAndTypesOption(attr)) {
this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship);
}
}
},
/*
Serializes a hasMany relationship as an array of objects containing only `id` and `type`
keys.
This has its use case on polymorphic hasMany relationships where the server is not storing
all records in the same table using STI, and therefore the `id` is not enough information
TODO: Make the default in Ember-data 3.0??
*/
_serializeHasManyAsIdsAndTypes: function (snapshot, json, relationship) {
var serializedKey = this.keyForAttribute(relationship.key, 'serialize');
var hasMany = snapshot.hasMany(relationship.key);
json[serializedKey] = _ember.default.A(hasMany).map(function (recordSnapshot) {
//
// I'm sure I'm being utterly naive here. Propably id is a configurate property and
// type too, and the modelName has to be normalized somehow.
//
return { id: recordSnapshot.id, type: recordSnapshot.modelName };
});
},
_serializeEmbeddedHasMany: function (snapshot, json, relationship) {
var serializedKey = this._getMappedKey(relationship.key, snapshot.type);
if (serializedKey === relationship.key && this.keyForRelationship) {
serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize");
}
(false && _ember.default.warn('The embedded relationship \'' + serializedKey + '\' is undefined for \'' + snapshot.modelName + '\' with id \'' + snapshot.id + '\'. Please include it in your original payload.', _ember.default.typeOf(snapshot.hasMany(relationship.key)) !== 'undefined', { id: 'ds.serializer.embedded-relationship-undefined' }));
json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship);
},
/*
Returns an array of embedded records serialized to JSON
*/
_generateSerializedHasMany: function (snapshot, relationship) {
var hasMany = snapshot.hasMany(relationship.key);
var manyArray = _ember.default.A(hasMany);
var ret = new Array(manyArray.length);
for (var i = 0; i < manyArray.length; i++) {
var embeddedSnapshot = manyArray[i];
var embeddedJson = embeddedSnapshot.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson);
ret[i] = embeddedJson;
}
return ret;
},
/**
When serializing an embedded record, modify the property (in the json payload)
that refers to the parent record (foreign key for relationship).
Serializing a `belongsTo` relationship removes the property that refers to the
parent record
Serializing a `hasMany` relationship does not remove the property that refers to
the parent record.
@method removeEmbeddedForeignKey
@param {DS.Snapshot} snapshot
@param {DS.Snapshot} embeddedSnapshot
@param {Object} relationship
@param {Object} json
*/
removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) {
if (relationship.kind === 'belongsTo') {
var parentRecord = snapshot.type.inverseFor(relationship.key, this.store);
if (parentRecord) {
var name = parentRecord.name;
var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName);
var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize');
if (parentKey) {
delete json[parentKey];
}
}
} /*else if (relationship.kind === 'hasMany') {
return;
}*/
},
// checks config for attrs option to embedded (always) - serialize and deserialize
hasEmbeddedAlwaysOption: function (attr) {
var option = this.attrsOption(attr);
return option && option.embedded === 'always';
},
// checks config for attrs option to serialize ids
hasSerializeRecordsOption: function (attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || option && option.serialize === 'records';
},
// checks config for attrs option to serialize records
hasSerializeIdsOption: function (attr) {
var option = this.attrsOption(attr);
return option && (option.serialize === 'ids' || option.serialize === 'id');
},
// checks config for attrs option to serialize records as objects containing id and types
hasSerializeIdsAndTypesOption: function (attr) {
var option = this.attrsOption(attr);
return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type');
},
// checks config for attrs option to serialize records
noSerializeOptionSpecified: function (attr) {
var option = this.attrsOption(attr);
return !(option && (option.serialize || option.embedded));
},
// checks config for attrs option to deserialize records
// a defined option object for a resource is treated the same as
// `deserialize: 'records'`
hasDeserializeRecordsOption: function (attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || option && option.deserialize === 'records';
},
attrsOption: function (attr) {
var attrs = this.get('attrs');
return attrs && (attrs[camelize(attr)] || attrs[attr]);
},
/**
@method _extractEmbeddedRecords
@private
*/
_extractEmbeddedRecords: function (serializer, store, typeClass, partial) {
var _this = this;
typeClass.eachRelationship(function (key, relationship) {
if (serializer.hasDeserializeRecordsOption(key)) {
if (relationship.kind === "hasMany") {
_this._extractEmbeddedHasMany(store, key, partial, relationship);
}
if (relationship.kind === "belongsTo") {
_this._extractEmbeddedBelongsTo(store, key, partial, relationship);
}
}
});
return partial;
},
/**
@method _extractEmbeddedHasMany
@private
*/
_extractEmbeddedHasMany: function (store, key, hash, relationshipMeta) {
var relationshipHash = get(hash, 'data.relationships.' + key + '.data');
if (!relationshipHash) {
return;
}
var hasMany = new Array(relationshipHash.length);
for (var i = 0; i < relationshipHash.length; i++) {
var item = relationshipHash[i];
var _normalizeEmbeddedRel = this._normalizeEmbeddedRelationship(store, relationshipMeta, item),
data = _normalizeEmbeddedRel.data,
included = _normalizeEmbeddedRel.included;
hash.included = hash.included || [];
hash.included.push(data);
if (included) {
var _hash$included;
(_hash$included = hash.included).push.apply(_hash$included, _toConsumableArray(included));
}
hasMany[i] = { id: data.id, type: data.type };
}
var relationship = { data: hasMany };
set(hash, 'data.relationships.' + key, relationship);
},
/**
@method _extractEmbeddedBelongsTo
@private
*/
_extractEmbeddedBelongsTo: function (store, key, hash, relationshipMeta) {
var relationshipHash = get(hash, 'data.relationships.' + key + '.data');
if (!relationshipHash) {
return;
}
var _normalizeEmbeddedRel2 = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash),
data = _normalizeEmbeddedRel2.data,
included = _normalizeEmbeddedRel2.included;
hash.included = hash.included || [];
hash.included.push(data);
if (included) {
var _hash$included2;
(_hash$included2 = hash.included).push.apply(_hash$included2, _toConsumableArray(included));
}
var belongsTo = { id: data.id, type: data.type };
var relationship = { data: belongsTo };
set(hash, 'data.relationships.' + key, relationship);
},
/**
@method _normalizeEmbeddedRelationship
@private
*/
_normalizeEmbeddedRelationship: function (store, relationshipMeta, relationshipHash) {
var modelName = relationshipMeta.type;
if (relationshipMeta.options.polymorphic) {
modelName = relationshipHash.type;
}
var modelClass = store.modelFor(modelName);
var serializer = store.serializerFor(modelName);
return serializer.normalize(modelClass, relationshipHash, null);
},
isEmbeddedRecordsMixin: true
});
});
define('ember-data/serializers/json-api', ['exports', 'ember', 'ember-inflector', 'ember-data/serializers/json', 'ember-data/-private'], function (exports, _ember, _emberInflector, _json, _private) {
'use strict';
exports.__esModule = true;
/**
@module ember-data
*/
var dasherize = _ember.default.String.dasherize;
/**
Ember Data 2.0 Serializer:
In Ember Data a Serializer is used to serialize and deserialize
records when they are transferred in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializing relationships.
`JSONAPISerializer` supports the http://jsonapi.org/ spec and is the
serializer recommended by Ember Data.
This serializer normalizes a JSON API payload that looks like:
```app/models/player.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
skill: DS.attr('string'),
gamesPlayed: DS.attr('number'),
club: DS.belongsTo('club')
});
```
```app/models/club.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
location: DS.attr('string'),
players: DS.hasMany('player')
});
```
```js
{
"data": [
{
"attributes": {
"name": "Benfica",
"location": "Portugal"
},
"id": "1",
"relationships": {
"players": {
"data": [
{
"id": "3",
"type": "players"
}
]
}
},
"type": "clubs"
}
],
"included": [
{
"attributes": {
"name": "Eusebio Silva Ferreira",
"skill": "Rocket shot",
"games-played": 431
},
"id": "3",
"relationships": {
"club": {
"data": {
"id": "1",
"type": "clubs"
}
}
},
"type": "players"
}
]
}
```
to the format that the Ember Data store expects.
### Customizing meta
Since a JSON API Document can have meta defined in multiple locations you can
use the specific serializer hooks if you need to customize the meta.
One scenario would be to camelCase the meta keys of your payload. The example
below shows how this could be done using `normalizeArrayResponse` and
`extractRelationship`.
```app/serializers/application.js
export default JSONAPISerializer.extend({
normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
let normalizedDocument = this._super(...arguments);
// Customize document meta
normalizedDocument.meta = camelCaseKeys(normalizedDocument.meta);
return normalizedDocument;
},
extractRelationship(relationshipHash) {
let normalizedRelationship = this._super(...arguments);
// Customize relationship meta
normalizedRelationship.meta = camelCaseKeys(normalizedRelationship.meta);
return normalizedRelationship;
}
});
```
@since 1.13.0
@class JSONAPISerializer
@namespace DS
@extends DS.JSONSerializer
*/
var JSONAPISerializer = _json.default.extend({
_normalizeDocumentHelper: function (documentHash) {
if (_ember.default.typeOf(documentHash.data) === 'object') {
documentHash.data = this._normalizeResourceHelper(documentHash.data);
} else if (Array.isArray(documentHash.data)) {
var ret = new Array(documentHash.data.length);
for (var i = 0; i < documentHash.data.length; i++) {
var data = documentHash.data[i];
ret[i] = this._normalizeResourceHelper(data);
}
documentHash.data = ret;
}
if (Array.isArray(documentHash.included)) {
var _ret = new Array(documentHash.included.length);
for (var _i = 0; _i < documentHash.included.length; _i++) {
var included = documentHash.included[_i];
_ret[_i] = this._normalizeResourceHelper(included);
}
documentHash.included = _ret;
}
return documentHash;
},
_normalizeRelationshipDataHelper: function (relationshipDataHash) {
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
var modelName = this.modelNameFromPayloadType(relationshipDataHash.type);
var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipDataHash.type);
if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) {
(false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a relationship. This has been deprecated in favor of modelNameFromPayloadType", false, {
id: 'ds.json-api-serializer.deprecated-model-name-for-relationship',
until: '3.0.0'
}));
modelName = deprecatedModelNameLookup;
}
relationshipDataHash.type = modelName;
} else {
relationshipDataHash.type = this.modelNameFromPayloadKey(relationshipDataHash.type);
}
return relationshipDataHash;
},
_normalizeResourceHelper: function (resourceHash) {
(false && _ember.default.assert(this.warnMessageForUndefinedType(), !_ember.default.isNone(resourceHash.type), {
id: 'ds.serializer.type-is-undefined'
}));
var modelName = void 0,
usedLookup = void 0;
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
modelName = this.modelNameFromPayloadType(resourceHash.type);
var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type);
usedLookup = 'modelNameFromPayloadType';
if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) {
(false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a resource. This has been deprecated in favor of modelNameFromPayloadType", false, {
id: 'ds.json-api-serializer.deprecated-model-name-for-resource',
until: '3.0.0'
}));
modelName = deprecatedModelNameLookup;
usedLookup = 'modelNameFromPayloadKey';
}
} else {
modelName = this.modelNameFromPayloadKey(resourceHash.type);
usedLookup = 'modelNameFromPayloadKey';
}
if (!this.store._hasModelFor(modelName)) {
(false && _ember.default.warn(this.warnMessageNoModelForType(modelName, resourceHash.type, usedLookup), false, {
id: 'ds.serializer.model-for-type-missing'
}));
return null;
}
var modelClass = this.store._modelFor(modelName);
var serializer = this.store.serializerFor(modelName);
var _serializer$normalize = serializer.normalize(modelClass, resourceHash),
data = _serializer$normalize.data;
return data;
},
pushPayload: function (store, payload) {
var normalizedPayload = this._normalizeDocumentHelper(payload);
if ((0, _private.isEnabled)('ds-pushpayload-return')) {
return store.push(normalizedPayload);
} else {
store.push(normalizedPayload);
}
},
_normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) {
var normalizedPayload = this._normalizeDocumentHelper(payload);
return normalizedPayload;
},
normalizeQueryRecordResponse: function () {
var normalized = this._super.apply(this, arguments);
(false && _ember.default.assert('Expected the primary data returned by the serializer for a `queryRecord` response to be a single object but instead it was an array.', !Array.isArray(normalized.data), {
id: 'ds.serializer.json-api.queryRecord-array-response'
}));
return normalized;
},
extractAttributes: function (modelClass, resourceHash) {
var _this = this;
var attributes = {};
if (resourceHash.attributes) {
modelClass.eachAttribute(function (key) {
var attributeKey = _this.keyForAttribute(key, 'deserialize');
if (resourceHash.attributes[attributeKey] !== undefined) {
attributes[key] = resourceHash.attributes[attributeKey];
}
if (false) {
if (resourceHash.attributes[attributeKey] === undefined && resourceHash.attributes[key] !== undefined) {
(false && _ember.default.assert('Your payload for \'' + modelClass.modelName + '\' contains \'' + key + '\', but your serializer is setup to look for \'' + attributeKey + '\'. This is most likely because Ember Data\'s JSON API serializer dasherizes attribute keys by default. You should subclass JSONAPISerializer and implement \'keyForAttribute(key) { return key; }\' to prevent Ember Data from customizing your attribute keys.', false));
}
}
});
}
return attributes;
},
extractRelationship: function (relationshipHash) {
if (_ember.default.typeOf(relationshipHash.data) === 'object') {
relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data);
}
if (Array.isArray(relationshipHash.data)) {
var ret = new Array(relationshipHash.data.length);
for (var i = 0; i < relationshipHash.data.length; i++) {
var data = relationshipHash.data[i];
ret[i] = this._normalizeRelationshipDataHelper(data);
}
relationshipHash.data = ret;
}
return relationshipHash;
},
extractRelationships: function (modelClass, resourceHash) {
var _this2 = this;
var relationships = {};
if (resourceHash.relationships) {
modelClass.eachRelationship(function (key, relationshipMeta) {
var relationshipKey = _this2.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
if (resourceHash.relationships[relationshipKey] !== undefined) {
var relationshipHash = resourceHash.relationships[relationshipKey];
relationships[key] = _this2.extractRelationship(relationshipHash);
}
if (false) {
if (resourceHash.relationships[relationshipKey] === undefined && resourceHash.relationships[key] !== undefined) {
(false && _ember.default.assert('Your payload for \'' + modelClass.modelName + '\' contains \'' + key + '\', but your serializer is setup to look for \'' + relationshipKey + '\'. This is most likely because Ember Data\'s JSON API serializer dasherizes relationship keys by default. You should subclass JSONAPISerializer and implement \'keyForRelationship(key) { return key; }\' to prevent Ember Data from customizing your relationship keys.', false));
}
}
});
}
return relationships;
},
_extractType: function (modelClass, resourceHash) {
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
var modelName = this.modelNameFromPayloadType(resourceHash.type);
var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type);
if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) {
(false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, {
id: 'ds.json-api-serializer.deprecated-model-name-for-polymorphic-type',
until: '3.0.0'
}));
modelName = deprecatedModelNameLookup;
}
return modelName;
} else {
return this.modelNameFromPayloadKey(resourceHash.type);
}
},
modelNameFromPayloadKey: function (key) {
return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(key));
},
payloadKeyFromModelName: function (modelName) {
return (0, _emberInflector.pluralize)(modelName);
},
normalize: function (modelClass, resourceHash) {
if (resourceHash.attributes) {
this.normalizeUsingDeclaredMapping(modelClass, resourceHash.attributes);
}
if (resourceHash.relationships) {
this.normalizeUsingDeclaredMapping(modelClass, resourceHash.relationships);
}
var data = {
id: this.extractId(modelClass, resourceHash),
type: this._extractType(modelClass, resourceHash),
attributes: this.extractAttributes(modelClass, resourceHash),
relationships: this.extractRelationships(modelClass, resourceHash)
};
this.applyTransforms(modelClass, data.attributes);
return { data: data };
},
keyForAttribute: function (key, method) {
return dasherize(key);
},
keyForRelationship: function (key, typeClass, method) {
return dasherize(key);
},
serialize: function (snapshot, options) {
var data = this._super.apply(this, arguments);
var payloadType = void 0;
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
payloadType = this.payloadTypeFromModelName(snapshot.modelName);
var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(snapshot.modelName);
if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) {
(false && !(false) && _ember.default.deprecate("You used payloadKeyFromModelName to customize how a type is serialized. Use payloadTypeFromModelName instead.", false, {
id: 'ds.json-api-serializer.deprecated-payload-type-for-model',
until: '3.0.0'
}));
payloadType = deprecatedPayloadTypeLookup;
}
} else {
payloadType = this.payloadKeyFromModelName(snapshot.modelName);
}
data.type = payloadType;
return { data: data };
},
serializeAttribute: function (snapshot, json, key, attribute) {
var type = attribute.type;
if (this._canSerialize(key)) {
json.attributes = json.attributes || {};
var value = snapshot.attr(key);
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value, attribute.options);
}
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key) {
payloadKey = this.keyForAttribute(key, 'serialize');
}
json.attributes[payloadKey] = value;
}
},
serializeBelongsTo: function (snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var belongsTo = snapshot.belongsTo(key);
if (belongsTo !== undefined) {
json.relationships = json.relationships || {};
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key) {
payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize');
}
var data = null;
if (belongsTo) {
var payloadType = void 0;
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
payloadType = this.payloadTypeFromModelName(belongsTo.modelName);
var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(belongsTo.modelName);
if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) {
(false && !(false) && _ember.default.deprecate("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, {
id: 'ds.json-api-serializer.deprecated-payload-type-for-belongs-to',
until: '3.0.0'
}));
payloadType = deprecatedPayloadTypeLookup;
}
} else {
payloadType = this.payloadKeyFromModelName(belongsTo.modelName);
}
data = {
type: payloadType,
id: belongsTo.id
};
}
json.relationships[payloadKey] = { data: data };
}
}
},
serializeHasMany: function (snapshot, json, relationship) {
var key = relationship.key;
var shouldSerializeHasMany = '_shouldSerializeHasMany';
if ((0, _private.isEnabled)("ds-check-should-serialize-relationships")) {
shouldSerializeHasMany = 'shouldSerializeHasMany';
}
if (this[shouldSerializeHasMany](snapshot, key, relationship)) {
var hasMany = snapshot.hasMany(key);
if (hasMany !== undefined) {
json.relationships = json.relationships || {};
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize');
}
var data = new Array(hasMany.length);
for (var i = 0; i < hasMany.length; i++) {
var item = hasMany[i];
var payloadType = void 0;
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
payloadType = this.payloadTypeFromModelName(item.modelName);
var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(item.modelName);
if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) {
(false && !(false) && _ember.default.deprecate("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, {
id: 'ds.json-api-serializer.deprecated-payload-type-for-has-many',
until: '3.0.0'
}));
payloadType = deprecatedPayloadTypeLookup;
}
} else {
payloadType = this.payloadKeyFromModelName(item.modelName);
}
data[i] = {
type: payloadType,
id: item.id
};
}
json.relationships[payloadKey] = { data: data };
}
}
}
});
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
JSONAPISerializer.reopen({
modelNameFromPayloadType: function (type) {
return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(type));
},
payloadTypeFromModelName: function (modelName) {
return (0, _emberInflector.pluralize)(modelName);
},
_hasCustomModelNameFromPayloadKey: function () {
return this.modelNameFromPayloadKey !== JSONAPISerializer.prototype.modelNameFromPayloadKey;
},
_hasCustomPayloadKeyFromModelName: function () {
return this.payloadKeyFromModelName !== JSONAPISerializer.prototype.payloadKeyFromModelName;
}
});
}
if (false) {
JSONAPISerializer.reopen({
willMergeMixin: function (props) {
var constructor = this.constructor;
(false && _ember.default.warn('You\'ve defined \'extractMeta\' in ' + constructor.toString() + ' which is not used for serializers extending JSONAPISerializer. Read more at http://emberjs.com/api/data/classes/DS.JSONAPISerializer.html#toc_customizing-meta on how to customize meta when using JSON API.', _ember.default.isNone(props.extractMeta) || props.extractMeta === _json.default.prototype.extractMeta, {
id: 'ds.serializer.json-api.extractMeta'
}));
(false && _ember.default.warn('The JSONAPISerializer does not work with the EmbeddedRecordsMixin because the JSON API spec does not describe how to format embedded resources.', !props.isEmbeddedRecordsMixin, {
id: 'ds.serializer.embedded-records-mixin-not-supported'
}));
},
warnMessageForUndefinedType: function () {
return 'Encountered a resource object with an undefined type (resolved resource using ' + this.constructor.toString() + ')';
},
warnMessageNoModelForType: function (modelName, originalType, usedLookup) {
return 'Encountered a resource object with type "' + originalType + '", but no model was found for model name "' + modelName + '" (resolved model name using \'' + this.constructor.toString() + '.' + usedLookup + '("' + originalType + '")\').';
}
});
}
exports.default = JSONAPISerializer;
});
define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/serializer', 'ember-data/-private'], function (exports, _ember, _serializer, _private) {
'use strict';
exports.__esModule = true;
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}
var get = _ember.default.get;
var isNone = _ember.default.isNone;
var assign = _ember.default.assign || _ember.default.merge;
/**
Ember Data 2.0 Serializer:
In Ember Data a Serializer is used to serialize and deserialize
records when they are transferred in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializing relationships.
By default, Ember Data uses and recommends the `JSONAPISerializer`.
`JSONSerializer` is useful for simpler or legacy backends that may
not support the http://jsonapi.org/ spec.
For example, given the following `User` model and JSON payload:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
friends: DS.hasMany('user'),
house: DS.belongsTo('location'),
name: DS.attr('string')
});
```
```js
{
id: 1,
name: 'Sebastian',
friends: [3, 4],
links: {
house: '/houses/lefkada'
}
}
```
`JSONSerializer` will normalize the JSON payload to the JSON API format that the
Ember Data store expects.
You can customize how JSONSerializer processes its payload by passing options in
the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks:
- To customize how a single record is normalized, use the `normalize` hook.
- To customize how `JSONSerializer` normalizes the whole server response, use the
`normalizeResponse` hook.
- To customize how `JSONSerializer` normalizes a specific response from the server,
use one of the many specific `normalizeResponse` hooks.
- To customize how `JSONSerializer` normalizes your id, attributes or relationships,
use the `extractId`, `extractAttributes` and `extractRelationships` hooks.
The `JSONSerializer` normalization process follows these steps:
- `normalizeResponse` - entry method to the serializer.
- `normalizeCreateRecordResponse` - a `normalizeResponse` for a specific operation is called.
- `normalizeSingleResponse`|`normalizeArrayResponse` - for methods like `createRecord` we expect
a single record back, while for methods like `findAll` we expect multiple records back.
- `normalize` - `normalizeArray` iterates and calls `normalize` for each of its records while `normalizeSingle`
calls it once. This is the method you most likely want to subclass.
- `extractId` | `extractAttributes` | `extractRelationships` - `normalize` delegates to these methods to
turn the record payload into the JSON API format.
@class JSONSerializer
@namespace DS
@extends DS.Serializer
*/
var JSONSerializer = _serializer.default.extend({
/**
The `primaryKey` is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
`primaryKey` property to match the `primaryKey` of your external
store.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
The `attrs` object can be used to declare a simple mapping between
property names on `DS.Model` records and payload keys in the
serialized JSON object representing the record. An object with the
property `key` can also be used to designate the attribute's key on
the response payload.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string'),
admin: DS.attr('boolean')
});
```
```app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: 'is_admin',
occupation: { key: 'career' }
}
});
```
You can also remove attributes by setting the `serialize` key to
`false` in your mapping object.
Example
```app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: { serialize: false },
occupation: { key: 'career' }
}
});
```
When serialized:
```javascript
{
"firstName": "Harry",
"lastName": "Houdini",
"career": "magician"
}
```
Note that the `admin` is now not included in the payload.
@property attrs
@type {Object}
*/
mergedProperties: ['attrs'],
applyTransforms: function (typeClass, data) {
var _this = this;
var attributes = get(typeClass, 'attributes');
typeClass.eachTransformedAttribute(function (key, typeClass) {
if (data[key] === undefined) {
return;
}
var transform = _this.transformFor(typeClass);
var transformMeta = attributes.get(key);
data[key] = transform.deserialize(data[key], transformMeta.options);
});
return data;
},
normalizeResponse: function (store, primaryModelClass, payload, id, requestType) {
switch (requestType) {
case 'findRecord':
return this.normalizeFindRecordResponse.apply(this, arguments);
case 'queryRecord':
return this.normalizeQueryRecordResponse.apply(this, arguments);
case 'findAll':
return this.normalizeFindAllResponse.apply(this, arguments);
case 'findBelongsTo':
return this.normalizeFindBelongsToResponse.apply(this, arguments);
case 'findHasMany':
return this.normalizeFindHasManyResponse.apply(this, arguments);
case 'findMany':
return this.normalizeFindManyResponse.apply(this, arguments);
case 'query':
return this.normalizeQueryResponse.apply(this, arguments);
case 'createRecord':
return this.normalizeCreateRecordResponse.apply(this, arguments);
case 'deleteRecord':
return this.normalizeDeleteRecordResponse.apply(this, arguments);
case 'updateRecord':
return this.normalizeUpdateRecordResponse.apply(this, arguments);
}
},
normalizeFindRecordResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse.apply(this, arguments);
},
normalizeQueryRecordResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse.apply(this, arguments);
},
normalizeFindAllResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse.apply(this, arguments);
},
normalizeFindBelongsToResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse.apply(this, arguments);
},
normalizeFindHasManyResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse.apply(this, arguments);
},
normalizeFindManyResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse.apply(this, arguments);
},
normalizeQueryResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse.apply(this, arguments);
},
normalizeCreateRecordResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeSaveResponse.apply(this, arguments);
},
normalizeDeleteRecordResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeSaveResponse.apply(this, arguments);
},
normalizeUpdateRecordResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeSaveResponse.apply(this, arguments);
},
normalizeSaveResponse: function (store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse.apply(this, arguments);
},
normalizeSingleResponse: function (store, primaryModelClass, payload, id, requestType) {
return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true);
},
normalizeArrayResponse: function (store, primaryModelClass, payload, id, requestType) {
return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false);
},
_normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) {
var documentHash = {
data: null,
included: []
};
var meta = this.extractMeta(store, primaryModelClass, payload);
if (meta) {
(false && _ember.default.assert('The `meta` returned from `extractMeta` has to be an object, not "' + _ember.default.typeOf(meta) + '".', _ember.default.typeOf(meta) === 'object'));
documentHash.meta = meta;
}
if (isSingle) {
var _normalize = this.normalize(primaryModelClass, payload),
data = _normalize.data,
included = _normalize.included;
documentHash.data = data;
if (included) {
documentHash.included = included;
}
} else {
var ret = new Array(payload.length);
for (var i = 0, l = payload.length; i < l; i++) {
var item = payload[i];
var _normalize2 = this.normalize(primaryModelClass, item),
_data = _normalize2.data,
_included = _normalize2.included;
if (_included) {
var _documentHash$include;
(_documentHash$include = documentHash.included).push.apply(_documentHash$include, _toConsumableArray(_included));
}
ret[i] = _data;
}
documentHash.data = ret;
}
return documentHash;
},
normalize: function (modelClass, resourceHash) {
var data = null;
if (resourceHash) {
this.normalizeUsingDeclaredMapping(modelClass, resourceHash);
if (_ember.default.typeOf(resourceHash.links) === 'object') {
this.normalizeUsingDeclaredMapping(modelClass, resourceHash.links);
}
data = {
id: this.extractId(modelClass, resourceHash),
type: modelClass.modelName,
attributes: this.extractAttributes(modelClass, resourceHash),
relationships: this.extractRelationships(modelClass, resourceHash)
};
this.applyTransforms(modelClass, data.attributes);
}
return { data: data };
},
extractId: function (modelClass, resourceHash) {
var primaryKey = get(this, 'primaryKey');
var id = resourceHash[primaryKey];
return (0, _private.coerceId)(id);
},
extractAttributes: function (modelClass, resourceHash) {
var _this2 = this;
var attributeKey = void 0;
var attributes = {};
modelClass.eachAttribute(function (key) {
attributeKey = _this2.keyForAttribute(key, 'deserialize');
if (resourceHash[attributeKey] !== undefined) {
attributes[key] = resourceHash[attributeKey];
}
});
return attributes;
},
extractRelationship: function (relationshipModelName, relationshipHash) {
if (_ember.default.isNone(relationshipHash)) {
return null;
}
/*
When `relationshipHash` is an object it usually means that the relationship
is polymorphic. It could however also be embedded resources that the
EmbeddedRecordsMixin has be able to process.
*/
if (_ember.default.typeOf(relationshipHash) === 'object') {
if (relationshipHash.id) {
relationshipHash.id = (0, _private.coerceId)(relationshipHash.id);
}
var modelClass = this.store.modelFor(relationshipModelName);
if (relationshipHash.type && !(0, _private.modelHasAttributeOrRelationshipNamedType)(modelClass)) {
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
var modelName = this.modelNameFromPayloadType(relationshipHash.type);
var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipHash.type);
if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) {
(false && !(false) && _ember.default.deprecate("You used modelNameFromPayloadKey to customize how a type is normalized. Use modelNameFromPayloadType instead", false, {
id: 'ds.json-serializer.deprecated-type-for-polymorphic-relationship',
until: '3.0.0'
}));
modelName = deprecatedModelNameLookup;
}
relationshipHash.type = modelName;
} else {
relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type);
}
}
return relationshipHash;
}
return { id: (0, _private.coerceId)(relationshipHash), type: relationshipModelName };
},
extractPolymorphicRelationship: function (relationshipModelName, relationshipHash, relationshipOptions) {
return this.extractRelationship(relationshipModelName, relationshipHash);
},
extractRelationships: function (modelClass, resourceHash) {
var _this3 = this;
var relationships = {};
modelClass.eachRelationship(function (key, relationshipMeta) {
var relationship = null;
var relationshipKey = _this3.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
if (resourceHash[relationshipKey] !== undefined) {
var data = null;
var relationshipHash = resourceHash[relationshipKey];
if (relationshipMeta.kind === 'belongsTo') {
if (relationshipMeta.options.polymorphic) {
// extracting a polymorphic belongsTo may need more information
// than the type and the hash (which might only be an id) for the
// relationship, hence we pass the key, resource and
// relationshipMeta too
data = _this3.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, { key: key, resourceHash: resourceHash, relationshipMeta: relationshipMeta });
} else {
data = _this3.extractRelationship(relationshipMeta.type, relationshipHash);
}
} else if (relationshipMeta.kind === 'hasMany') {
if (!_ember.default.isNone(relationshipHash)) {
data = new Array(relationshipHash.length);
for (var i = 0, l = relationshipHash.length; i < l; i++) {
var item = relationshipHash[i];
data[i] = _this3.extractRelationship(relationshipMeta.type, item);
}
}
}
relationship = { data: data };
}
var linkKey = _this3.keyForLink(key, relationshipMeta.kind);
if (resourceHash.links && resourceHash.links[linkKey] !== undefined) {
var related = resourceHash.links[linkKey];
relationship = relationship || {};
relationship.links = { related: related };
}
if (relationship) {
relationships[key] = relationship;
}
});
return relationships;
},
modelNameFromPayloadKey: function (key) {
return (0, _private.normalizeModelName)(key);
},
normalizeRelationships: function (typeClass, hash) {
var _this4 = this;
var payloadKey = void 0;
if (this.keyForRelationship) {
typeClass.eachRelationship(function (key, relationship) {
payloadKey = _this4.keyForRelationship(key, relationship.kind, 'deserialize');
if (key === payloadKey) {
return;
}
if (hash[payloadKey] === undefined) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
});
}
},
normalizeUsingDeclaredMapping: function (modelClass, hash) {
var attrs = get(this, 'attrs');
var normalizedKey = void 0;
var payloadKey = void 0;
if (attrs) {
for (var key in attrs) {
normalizedKey = payloadKey = this._getMappedKey(key, modelClass);
if (hash[payloadKey] === undefined) {
continue;
}
if (get(modelClass, 'attributes').has(key)) {
normalizedKey = this.keyForAttribute(key);
}
if (get(modelClass, 'relationshipsByName').has(key)) {
normalizedKey = this.keyForRelationship(key);
}
if (payloadKey !== normalizedKey) {
hash[normalizedKey] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
_getMappedKey: function (key, modelClass) {
(false && _ember.default.warn('There is no attribute or relationship with the name `' + key + '` on `' + modelClass.modelName + '`. Check your serializers attrs hash.', get(modelClass, 'attributes').has(key) || get(modelClass, 'relationshipsByName').has(key), {
id: 'ds.serializer.no-mapped-attrs-key'
}));
var attrs = get(this, 'attrs');
var mappedKey = void 0;
if (attrs && attrs[key]) {
mappedKey = attrs[key];
//We need to account for both the { title: 'post_title' } and
//{ title: { key: 'post_title' }} forms
if (mappedKey.key) {
mappedKey = mappedKey.key;
}
if (typeof mappedKey === 'string') {
key = mappedKey;
}
}
return key;
},
_canSerialize: function (key) {
var attrs = get(this, 'attrs');
return !attrs || !attrs[key] || attrs[key].serialize !== false;
},
_mustSerialize: function (key) {
var attrs = get(this, 'attrs');
return attrs && attrs[key] && attrs[key].serialize === true;
},
shouldSerializeHasMany: function (snapshot, key, relationship) {
if (this._shouldSerializeHasMany !== JSONSerializer.prototype._shouldSerializeHasMany) {
(false && !(false) && _ember.default.deprecate('The private method _shouldSerializeHasMany has been promoted to the public API. Please remove the underscore to use the public shouldSerializeHasMany method.', false, {
id: 'ds.serializer.private-should-serialize-has-many',
until: '3.0.0'
}));
}
return this._shouldSerializeHasMany(snapshot, key, relationship);
},
_shouldSerializeHasMany: function (snapshot, key, relationship) {
var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store);
if (this._mustSerialize(key)) {
return true;
}
return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany');
},
serialize: function (snapshot, options) {
var _this5 = this;
var json = {};
if (options && options.includeId) {
if ((0, _private.isEnabled)('ds-serialize-id')) {
this.serializeId(snapshot, json, get(this, 'primaryKey'));
} else {
var id = snapshot.id;
if (id) {
json[get(this, 'primaryKey')] = id;
}
}
}
snapshot.eachAttribute(function (key, attribute) {
_this5.serializeAttribute(snapshot, json, key, attribute);
});
snapshot.eachRelationship(function (key, relationship) {
if (relationship.kind === 'belongsTo') {
_this5.serializeBelongsTo(snapshot, json, relationship);
} else if (relationship.kind === 'hasMany') {
_this5.serializeHasMany(snapshot, json, relationship);
}
});
return json;
},
serializeIntoHash: function (hash, typeClass, snapshot, options) {
assign(hash, this.serialize(snapshot, options));
},
serializeAttribute: function (snapshot, json, key, attribute) {
if (this._canSerialize(key)) {
var type = attribute.type;
var value = snapshot.attr(key);
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value, attribute.options);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key && this.keyForAttribute) {
payloadKey = this.keyForAttribute(key, 'serialize');
}
json[payloadKey] = value;
}
},
serializeBelongsTo: function (snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var belongsToId = snapshot.belongsTo(key, { id: true });
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "belongsTo", "serialize");
}
//Need to check whether the id is there for new&async records
if (isNone(belongsToId)) {
json[payloadKey] = null;
} else {
json[payloadKey] = belongsToId;
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(snapshot, json, relationship);
}
}
},
serializeHasMany: function (snapshot, json, relationship) {
var key = relationship.key;
var shouldSerializeHasMany = '_shouldSerializeHasMany';
if ((0, _private.isEnabled)("ds-check-should-serialize-relationships")) {
shouldSerializeHasMany = 'shouldSerializeHasMany';
}
if (this[shouldSerializeHasMany](snapshot, key, relationship)) {
var hasMany = snapshot.hasMany(key, { ids: true });
if (hasMany !== undefined) {
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "hasMany", "serialize");
}
json[payloadKey] = hasMany;
// TODO support for polymorphic manyToNone and manyToMany relationships
}
}
},
serializePolymorphicType: function () {},
extractMeta: function (store, modelClass, payload) {
if (payload && payload['meta'] !== undefined) {
var meta = payload.meta;
delete payload.meta;
return meta;
}
},
extractErrors: function (store, typeClass, payload, id) {
var _this6 = this;
if (payload && typeof payload === 'object' && payload.errors) {
payload = (0, _private.errorsArrayToHash)(payload.errors);
this.normalizeUsingDeclaredMapping(typeClass, payload);
typeClass.eachAttribute(function (name) {
var key = _this6.keyForAttribute(name, 'deserialize');
if (key !== name && payload[key] !== undefined) {
payload[name] = payload[key];
delete payload[key];
}
});
typeClass.eachRelationship(function (name) {
var key = _this6.keyForRelationship(name, 'deserialize');
if (key !== name && payload[key] !== undefined) {
payload[name] = payload[key];
delete payload[key];
}
});
}
return payload;
},
keyForAttribute: function (key, method) {
return key;
},
keyForRelationship: function (key, typeClass, method) {
return key;
},
keyForLink: function (key, kind) {
return key;
},
transformFor: function (attributeType, skipAssertion) {
var transform = (0, _private.getOwner)(this).lookup('transform:' + attributeType);
(false && _ember.default.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform));
return transform;
}
});
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
JSONSerializer.reopen({
modelNameFromPayloadType: function (type) {
return (0, _private.normalizeModelName)(type);
},
_hasCustomModelNameFromPayloadKey: function () {
return this.modelNameFromPayloadKey !== JSONSerializer.prototype.modelNameFromPayloadKey;
}
});
}
if ((0, _private.isEnabled)("ds-serialize-id")) {
JSONSerializer.reopen({
serializeId: function (snapshot, json, primaryKey) {
var id = snapshot.id;
if (id) {
json[primaryKey] = id;
}
}
});
}
exports.default = JSONSerializer;
});
define('ember-data/serializers/rest', ['exports', 'ember', 'ember-inflector', 'ember-data/serializers/json', 'ember-data/-private'], function (exports, _ember, _emberInflector, _json, _private) {
'use strict';
exports.__esModule = true;
function _toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return Array.from(arr);
}
}
var camelize = _ember.default.String.camelize;
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to define
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Firebase, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
keyForAttribute(attr, method) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter, and
the method (`serialize` or `deserialize`) as the third parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
var RESTSerializer = _json.default.extend({
keyForPolymorphicType: function (key, typeClass, method) {
var relationshipKey = this.keyForRelationship(key);
return relationshipKey + 'Type';
},
normalize: function (modelClass, resourceHash, prop) {
if (this.normalizeHash && this.normalizeHash[prop]) {
(false && !(false) && _ember.default.deprecate('`RESTSerializer.normalizeHash` has been deprecated. Please use `serializer.normalize` to modify the payload of single resources.', false, {
id: 'ds.serializer.normalize-hash-deprecated',
until: '3.0.0'
}));
this.normalizeHash[prop](resourceHash);
}
return this._super(modelClass, resourceHash);
},
_normalizeArray: function (store, modelName, arrayHash, prop) {
var _this = this;
var documentHash = {
data: [],
included: []
};
var modelClass = store.modelFor(modelName);
var serializer = store.serializerFor(modelName);
_ember.default.makeArray(arrayHash).forEach(function (hash) {
var _normalizePolymorphic = _this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer),
data = _normalizePolymorphic.data,
included = _normalizePolymorphic.included;
documentHash.data.push(data);
if (included) {
var _documentHash$include;
(_documentHash$include = documentHash.included).push.apply(_documentHash$include, _toConsumableArray(included));
}
});
return documentHash;
},
_normalizePolymorphicRecord: function (store, hash, prop, primaryModelClass, primarySerializer) {
var serializer = primarySerializer;
var modelClass = primaryModelClass;
var primaryHasTypeAttribute = (0, _private.modelHasAttributeOrRelationshipNamedType)(primaryModelClass);
if (!primaryHasTypeAttribute && hash.type) {
// Support polymorphic records in async relationships
var modelName = void 0;
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
modelName = this.modelNameFromPayloadType(hash.type);
var deprecatedModelNameLookup = this.modelNameFromPayloadKey(hash.type);
if (modelName !== deprecatedModelNameLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) {
(false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This is has been deprecated in favor of modelNameFromPayloadType", false, {
id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type',
until: '3.0.0'
}));
modelName = deprecatedModelNameLookup;
}
} else {
modelName = this.modelNameFromPayloadKey(hash.type);
}
if (store._hasModelFor(modelName)) {
serializer = store.serializerFor(modelName);
modelClass = store.modelFor(modelName);
}
}
return serializer.normalize(modelClass, hash, prop);
},
_normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) {
var documentHash = {
data: null,
included: []
};
var meta = this.extractMeta(store, primaryModelClass, payload);
if (meta) {
(false && _ember.default.assert('The `meta` returned from `extractMeta` has to be an object, not "' + _ember.default.typeOf(meta) + '".', _ember.default.typeOf(meta) === 'object'));
documentHash.meta = meta;
}
var keys = Object.keys(payload);
for (var i = 0, length = keys.length; i < length; i++) {
var prop = keys[i];
var modelName = prop;
var forcedSecondary = false;
/*
If you want to provide sideloaded records of the same type that the
primary data you can do that by prefixing the key with `_`.
Example
```
{
users: [
{ id: 1, title: 'Tom', manager: 3 },
{ id: 2, title: 'Yehuda', manager: 3 }
],
_users: [
{ id: 3, title: 'Tomster' }
]
}
```
This forces `_users` to be added to `included` instead of `data`.
*/
if (prop.charAt(0) === '_') {
forcedSecondary = true;
modelName = prop.substr(1);
}
var typeName = this.modelNameFromPayloadKey(modelName);
if (!store.modelFactoryFor(typeName)) {
(false && _ember.default.warn(this.warnMessageNoModelForKey(modelName, typeName), false, {
id: 'ds.serializer.model-for-key-missing'
}));
continue;
}
var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryModelClass);
var value = payload[prop];
if (value === null) {
continue;
}
if (false) {
var isQueryRecordAnArray = requestType === 'queryRecord' && isPrimary && Array.isArray(value);
var message = "The adapter returned an array for the primary data of a `queryRecord` response. This is deprecated as `queryRecord` should return a single record.";
(false && !(!isQueryRecordAnArray) && _ember.default.deprecate(message, !isQueryRecordAnArray, {
id: 'ds.serializer.rest.queryRecord-array-response',
until: '3.0'
}));
}
/*
Support primary data as an object instead of an array.
Example
```
{
user: { id: 1, title: 'Tom', manager: 3 }
}
```
*/
if (isPrimary && !Array.isArray(value)) {
var _normalizePolymorphic2 = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this),
_data = _normalizePolymorphic2.data,
_included = _normalizePolymorphic2.included;
documentHash.data = _data;
if (_included) {
var _documentHash$include2;
(_documentHash$include2 = documentHash.included).push.apply(_documentHash$include2, _toConsumableArray(_included));
}
continue;
}
var _normalizeArray = this._normalizeArray(store, typeName, value, prop),
data = _normalizeArray.data,
included = _normalizeArray.included;
if (included) {
var _documentHash$include3;
(_documentHash$include3 = documentHash.included).push.apply(_documentHash$include3, _toConsumableArray(included));
}
if (isSingle) {
data.forEach(function (resource) {
/*
Figures out if this is the primary record or not.
It's either:
1. The record with the same ID as the original request
2. If it's a newly created record without an ID, the first record
in the array
*/
var isUpdatedRecord = isPrimary && (0, _private.coerceId)(resource.id) === id;
var isFirstCreatedRecord = isPrimary && !id && !documentHash.data;
if (isFirstCreatedRecord || isUpdatedRecord) {
documentHash.data = resource;
} else {
documentHash.included.push(resource);
}
});
} else {
if (isPrimary) {
documentHash.data = data;
} else {
if (data) {
var _documentHash$include4;
(_documentHash$include4 = documentHash.included).push.apply(_documentHash$include4, _toConsumableArray(data));
}
}
}
}
return documentHash;
},
isPrimaryType: function (store, typeName, primaryTypeClass) {
return store.modelFor(typeName) === primaryTypeClass;
},
pushPayload: function (store, payload) {
var documentHash = {
data: [],
included: []
};
for (var prop in payload) {
var modelName = this.modelNameFromPayloadKey(prop);
if (!store.modelFactoryFor(modelName)) {
(false && _ember.default.warn(this.warnMessageNoModelForKey(prop, modelName), false, {
id: 'ds.serializer.model-for-key-missing'
}));
continue;
}
var type = store.modelFor(modelName);
var typeSerializer = store.serializerFor(type.modelName);
_ember.default.makeArray(payload[prop]).forEach(function (hash) {
var _typeSerializer$norma = typeSerializer.normalize(type, hash, prop),
data = _typeSerializer$norma.data,
included = _typeSerializer$norma.included;
documentHash.data.push(data);
if (included) {
var _documentHash$include5;
(_documentHash$include5 = documentHash.included).push.apply(_documentHash$include5, _toConsumableArray(included));
}
});
}
if ((0, _private.isEnabled)('ds-pushpayload-return')) {
return store.push(documentHash);
} else {
store.push(documentHash);
}
},
modelNameFromPayloadKey: function (key) {
return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(key));
},
serialize: function (snapshot, options) {
return this._super.apply(this, arguments);
},
serializeIntoHash: function (hash, typeClass, snapshot, options) {
var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName);
hash[normalizedRootKey] = this.serialize(snapshot, options);
},
payloadKeyFromModelName: function (modelName) {
return camelize(modelName);
},
serializePolymorphicType: function (snapshot, json, relationship) {
var key = relationship.key;
var typeKey = this.keyForPolymorphicType(key, relationship.type, 'serialize');
var belongsTo = snapshot.belongsTo(key);
// old way of getting the key for the polymorphic type
key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key;
key = key + 'Type';
// The old way of serializing the type of a polymorphic record used
// `keyForAttribute`, which is not correct. The next code checks if the old
// way is used and if it differs from the new way of using
// `keyForPolymorphicType`. If this is the case, a deprecation warning is
// logged and the old way is restored (so nothing breaks).
if (key !== typeKey && this.keyForPolymorphicType === RESTSerializer.prototype.keyForPolymorphicType) {
(false && !(false) && _ember.default.deprecate("The key to serialize the type of a polymorphic record is created via keyForAttribute which has been deprecated. Use the keyForPolymorphicType hook instead.", false, {
id: 'ds.rest-serializer.deprecated-key-for-polymorphic-type',
until: '3.0.0'
}));
typeKey = key;
}
if (_ember.default.isNone(belongsTo)) {
json[typeKey] = null;
} else {
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
json[typeKey] = this.payloadTypeFromModelName(belongsTo.modelName);
} else {
json[typeKey] = camelize(belongsTo.modelName);
}
}
},
extractPolymorphicRelationship: function (relationshipType, relationshipHash, relationshipOptions) {
var key = relationshipOptions.key,
resourceHash = relationshipOptions.resourceHash,
relationshipMeta = relationshipOptions.relationshipMeta;
// A polymorphic belongsTo relationship can be present in the payload
// either in the form where the `id` and the `type` are given:
//
// {
// message: { id: 1, type: 'post' }
// }
//
// or by the `id` and a `<relationship>Type` attribute:
//
// {
// message: 1,
// messageType: 'post'
// }
//
// The next code checks if the latter case is present and returns the
// corresponding JSON-API representation. The former case is handled within
// the base class JSONSerializer.
var isPolymorphic = relationshipMeta.options.polymorphic;
var typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize');
if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') {
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
var payloadType = resourceHash[typeProperty];
var type = this.modelNameFromPayloadType(payloadType);
var deprecatedTypeLookup = this.modelNameFromPayloadKey(payloadType);
if (payloadType !== deprecatedTypeLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) {
(false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, {
id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type',
until: '3.0.0'
}));
type = deprecatedTypeLookup;
}
return {
id: relationshipHash,
type: type
};
} else {
var _type = this.modelNameFromPayloadKey(resourceHash[typeProperty]);
return {
id: relationshipHash,
type: _type
};
}
}
return this._super.apply(this, arguments);
}
});
if ((0, _private.isEnabled)("ds-payload-type-hooks")) {
RESTSerializer.reopen({
modelNameFromPayloadType: function (payloadType) {
return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(payloadType));
},
payloadTypeFromModelName: function (modelName) {
return camelize(modelName);
},
_hasCustomModelNameFromPayloadKey: function () {
return this.modelNameFromPayloadKey !== RESTSerializer.prototype.modelNameFromPayloadKey;
},
_hasCustomModelNameFromPayloadType: function () {
return this.modelNameFromPayloadType !== RESTSerializer.prototype.modelNameFromPayloadType;
},
_hasCustomPayloadTypeFromModelName: function () {
return this.payloadTypeFromModelName !== RESTSerializer.prototype.payloadTypeFromModelName;
},
_hasCustomPayloadKeyFromModelName: function () {
return this.payloadKeyFromModelName !== RESTSerializer.prototype.payloadKeyFromModelName;
}
});
}
if (false) {
RESTSerializer.reopen({
warnMessageNoModelForKey: function (prop, typeKey) {
return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + prop + '"))';
}
});
}
exports.default = RESTSerializer;
});
define('ember-data/setup-container', ['exports', 'ember-data/-private', 'ember-data/serializers/json-api', 'ember-data/serializers/json', 'ember-data/serializers/rest', 'ember-data/adapters/json-api', 'ember-data/adapters/rest', 'ember-data/transforms/number', 'ember-data/transforms/date', 'ember-data/transforms/string', 'ember-data/transforms/boolean'], function (exports, _private, _jsonApi, _json, _rest, _jsonApi2, _rest2, _number, _date, _string, _boolean) {
'use strict';
exports.__esModule = true;
exports.default = setupContainer;
function has(applicationOrRegistry, fullName) {
if (applicationOrRegistry.has) {
// < 2.1.0
return applicationOrRegistry.has(fullName);
} else {
// 2.1.0+
return applicationOrRegistry.hasRegistration(fullName);
}
}
/*
Configures a registry for use with an Ember-Data
store. Accepts an optional namespace argument.
@method initializeStore
@param {Ember.Registry} registry
*/
function initializeStore(registry) {
// registry.optionsForType for Ember < 2.1.0
// application.registerOptionsForType for Ember 2.1.0+
var registerOptionsForType = registry.registerOptionsForType || registry.optionsForType;
registerOptionsForType.call(registry, 'serializer', { singleton: false });
registerOptionsForType.call(registry, 'adapter', { singleton: false });
registry.register('serializer:-default', _json.default);
registry.register('serializer:-rest', _rest.default);
registry.register('adapter:-rest', _rest2.default);
registry.register('adapter:-json-api', _jsonApi2.default);
registry.register('serializer:-json-api', _jsonApi.default);
if (!has(registry, 'service:store')) {
registry.register('service:store', _private.Store);
}
}
/*
Configures a registry with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeDebugAdapter
@param {Ember.Registry} registry
*/
function initializeDataAdapter(registry) {
registry.register('data-adapter:main', _private.DebugAdapter);
}
/*
Configures a registry with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeStoreInjections
@param {Ember.Registry} registry
*/
function initializeStoreInjections(registry) {
// registry.injection for Ember < 2.1.0
// application.inject for Ember 2.1.0+
var inject = registry.inject || registry.injection;
inject.call(registry, 'controller', 'store', 'service:store');
inject.call(registry, 'route', 'store', 'service:store');
inject.call(registry, 'data-adapter', 'store', 'service:store');
}
/*
Configures a registry for use with Ember-Data
transforms.
@method initializeTransforms
@param {Ember.Registry} registry
*/
function initializeTransforms(registry) {
registry.register('transform:boolean', _boolean.default);
registry.register('transform:date', _date.default);
registry.register('transform:number', _number.default);
registry.register('transform:string', _string.default);
}
function setupContainer(application) {
initializeDataAdapter(application);
initializeTransforms(application);
initializeStoreInjections(application);
initializeStore(application);
}
});
define('ember-data/store', ['exports', 'ember-data/-private'], function (exports, _private) {
'use strict';
exports.__esModule = true;
Object.defineProperty(exports, 'default', {
enumerable: true,
get: function () {
return _private.Store;
}
});
});
define('ember-data/transform', ['exports', 'ember-data/transforms/transform'], function (exports, _transform) {
'use strict';
exports.__esModule = true;
Object.defineProperty(exports, 'default', {
enumerable: true,
get: function () {
return _transform.default;
}
});
});
define('ember-data/transforms/boolean', ['exports', 'ember', 'ember-data/transforms/transform'], function (exports, _ember, _transform) {
'use strict';
exports.__esModule = true;
var isNone = _ember.default.isNone;
exports.default = _transform.default.extend({
deserialize: function (serialized, options) {
var type = typeof serialized;
if (isNone(serialized) && options.allowNull === true) {
return null;
}
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function (deserialized, options) {
if (isNone(deserialized) && options.allowNull === true) {
return null;
}
return Boolean(deserialized);
}
});
});
define('ember-data/transforms/date', ['exports', 'ember-data/transforms/transform', 'ember'], function (exports, _transform, _ember) {
'use strict';
exports.__esModule = true;
_ember.default.Date = _ember.default.Date || {};
/**
Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
© 2011 Colin Snover <http://zetafleet.com>
Released under MIT license.
@class Date
@namespace Ember
@static
@deprecated
*/
_ember.default.Date.parse = function (date) {
(false && !(false) && _ember.default.deprecate('Ember.Date.parse is deprecated because Safari 5-, IE8-, and\n Firefox 3.6- are no longer supported (see\n https://github.com/csnover/js-iso8601 for the history of this issue).\n Please use Date.parse instead', false, {
id: 'ds.ember.date.parse-deprecate',
until: '3.0.0'
}));
return Date.parse(date);
};
/**
The `DS.DateTransform` class is used to serialize and deserialize
date attributes on Ember Data record objects. This transform is used
when `date` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601)
standard.
```app/models/score.js
import DS from 'ember-data';
export default DS.Model.extend({
value: DS.attr('number'),
player: DS.belongsTo('player'),
date: DS.attr('date')
});
```
@class DateTransform
@extends DS.Transform
@namespace DS
*/
exports.default = _transform.default.extend({
deserialize: function (serialized) {
var type = typeof serialized;
if (type === "string") {
var offset = serialized.indexOf('+');
if (offset !== -1 && serialized.length - 3 === offset) {
(false && !(false) && _ember.default.deprecate('The ECMA2015 Spec for ISO 8601 dates does not allow for shorthand timezone offsets such as +00.\n Ember Data\'s normalization of date\'s allowing for this shorthand has been deprecated, please update your API to return\n UTC dates formatted with \xB1hh:mm timezone offsets or implement a custom UTC transform.', false, {
id: 'ds.attr.date.normalize-utc',
until: '3.0.0'
}));
return new Date(serialized + ':00');
// this is a phantom specific bug fix in which +0000 is not supported
} else if (offset !== -1 && serialized.length - 5 === offset) {
offset += 3;
return new Date(serialized.slice(0, offset) + ':' + serialized.slice(offset));
}
return new Date(serialized);
} else if (type === "number") {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is null return null
// if the value is not present in the data return undefined
return serialized;
} else {
return null;
}
},
serialize: function (date) {
if (date instanceof Date && !isNaN(date)) {
return date.toISOString();
} else {
return null;
}
}
});
});
define('ember-data/transforms/number', ['exports', 'ember', 'ember-data/transforms/transform'], function (exports, _ember, _transform) {
'use strict';
exports.__esModule = true;
var empty = _ember.default.isEmpty;
function isNumber(value) {
return value === value && value !== Infinity && value !== -Infinity;
}
/**
The `DS.NumberTransform` class is used to serialize and deserialize
numeric attributes on Ember Data record objects. This transform is
used when `number` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```app/models/score.js
import DS from 'ember-data';
export default DS.Model.extend({
value: DS.attr('number'),
player: DS.belongsTo('player'),
date: DS.attr('date')
});
```
@class NumberTransform
@extends DS.Transform
@namespace DS
*/
exports.default = _transform.default.extend({
deserialize: function (serialized) {
var transformed = void 0;
if (empty(serialized)) {
return null;
} else {
transformed = Number(serialized);
return isNumber(transformed) ? transformed : null;
}
},
serialize: function (deserialized) {
var transformed = void 0;
if (empty(deserialized)) {
return null;
} else {
transformed = Number(deserialized);
return isNumber(transformed) ? transformed : null;
}
}
});
});
define('ember-data/transforms/string', ['exports', 'ember', 'ember-data/transforms/transform'], function (exports, _ember, _transform) {
'use strict';
exports.__esModule = true;
var none = _ember.default.isNone;
/**
The `DS.StringTransform` class is used to serialize and deserialize
string attributes on Ember Data record objects. This transform is
used when `string` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
isAdmin: DS.attr('boolean'),
name: DS.attr('string'),
email: DS.attr('string')
});
```
@class StringTransform
@extends DS.Transform
@namespace DS
*/
exports.default = _transform.default.extend({
deserialize: function (serialized) {
return none(serialized) ? null : String(serialized);
},
serialize: function (deserialized) {
return none(deserialized) ? null : String(deserialized);
}
});
});
define('ember-data/transforms/transform', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = _ember.default.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize(deserialized, options) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
@param options hash of options passed to `DS.attr`
@return The serialized value
*/
serialize: null,
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize(serialized, options) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param serialized The serialized value
@param options hash of options passed to `DS.attr`
@return The deserialized value
*/
deserialize: null
});
});
define("ember-data/version", ["exports"], function (exports) {
"use strict";
exports.__esModule = true;
exports.default = "2.15.0-beta.1";
});
define("ember-inflector", ["module", "exports", "ember", "ember-inflector/lib/system", "ember-inflector/lib/ext/string"], function (module, exports, _ember, _system) {
"use strict";
exports.__esModule = true;
exports.defaultRules = exports.singularize = exports.pluralize = undefined;
/* global define, module */
_system.Inflector.defaultRules = _system.defaultRules;
_ember.default.Inflector = _system.Inflector;
_ember.default.String.pluralize = _system.pluralize;
_ember.default.String.singularize = _system.singularize;
exports.default = _system.Inflector;
exports.pluralize = _system.pluralize;
exports.singularize = _system.singularize;
exports.defaultRules = _system.defaultRules;
if (typeof define !== 'undefined' && define.amd) {
define('ember-inflector', ['exports'], function (__exports__) {
__exports__['default'] = _system.Inflector;
__exports__.pluralize = _system.pluralize;
__exports__.singularize = _system.singularize;
return __exports__;
});
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = _system.Inflector;
_system.Inflector.singularize = _system.singularize;
_system.Inflector.pluralize = _system.pluralize;
}
});
define('ember-inflector/lib/ext/string', ['ember', 'ember-inflector/lib/system/string'], function (_ember, _string) {
'use strict';
if (_ember.default.EXTEND_PROTOTYPES === true || _ember.default.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function () {
return (0, _string.pluralize)(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function () {
return (0, _string.singularize)(this);
};
}
});
define('ember-inflector/lib/helpers/pluralize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _makeHelper) {
'use strict';
exports.__esModule = true;
exports.default = (0, _makeHelper.default)(function (params, hash) {
var count = void 0,
word = void 0,
withoutCount = false;
if (params.length === 1) {
word = params[0];
return (0, _emberInflector.pluralize)(word);
} else {
count = params[0];
word = params[1];
if (hash["without-count"]) {
withoutCount = hash["without-count"];
}
if (parseFloat(count) !== 1) {
word = (0, _emberInflector.pluralize)(word);
}
return withoutCount ? word : count + " " + word;
}
});
});
define('ember-inflector/lib/helpers/singularize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _makeHelper) {
'use strict';
exports.__esModule = true;
exports.default = (0, _makeHelper.default)(function (params) {
return (0, _emberInflector.singularize)(params[0]);
});
});
define("ember-inflector/lib/system", ["exports", "ember-inflector/lib/system/inflector", "ember-inflector/lib/system/string", "ember-inflector/lib/system/inflections"], function (exports, _inflector, _string, _inflections) {
"use strict";
exports.__esModule = true;
exports.defaultRules = exports.pluralize = exports.singularize = exports.Inflector = undefined;
_inflector.default.inflector = new _inflector.default(_inflections.default);
exports.Inflector = _inflector.default;
exports.singularize = _string.singularize;
exports.pluralize = _string.pluralize;
exports.defaultRules = _inflections.default;
});
define('ember-inflector/lib/system/inflections', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = {
plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status|bonus)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']],
singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status|bonus)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']],
irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']],
uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police']
};
});
define('ember-inflector/lib/system/inflector', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
var capitalize = _ember.default.String.capitalize;
var BLANK_REGEX = /^\s*$/;
var LAST_WORD_DASHED_REGEX = /([\w/-]+[_/\s-])([a-z\d]+$)/;
var LAST_WORD_CAMELIZED_REGEX = /([\w/\s-]+)([A-Z][a-z\d]*$)/;
var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/;
function loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
//pluralizing
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregular[pair[1].toLowerCase()] = pair[1];
//singularizing
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
rules.irregularInverse[pair[0].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow'); //=> 'kine'
inflector.singularize('kine'); //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice'); // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice'); // => 'advice'
inflector.pluralize('formula'); // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula'); // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [
[ /$/, 's' ]
],
singular: [
[ /\s$/, '' ]
],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || makeDictionary();
ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary();
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: makeDictionary(),
irregularInverse: makeDictionary(),
uncountable: makeDictionary()
};
loadUncountable(rules, ruleSet.uncountable);
loadIrregular(rules, ruleSet.irregularPairs);
this.enableCache();
}
if (!Object.create && !Object.create(null).hasOwnProperty) {
throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg");
}
function makeDictionary() {
var cache = Object.create(null);
cache['_dict'] = null;
delete cache['_dict'];
return cache;
}
Inflector.prototype = {
/**
@public
As inflections can be costly, and commonly the same subset of words are repeatedly
inflected an optional cache is provided.
@method enableCache
*/
enableCache: function () {
this.purgeCache();
this.singularize = function (word) {
this._cacheUsed = true;
return this._sCache[word] || (this._sCache[word] = this._singularize(word));
};
this.pluralize = function (word) {
this._cacheUsed = true;
return this._pCache[word] || (this._pCache[word] = this._pluralize(word));
};
},
/**
@public
@method purgedCache
*/
purgeCache: function () {
this._cacheUsed = false;
this._sCache = makeDictionary();
this._pCache = makeDictionary();
},
/**
@public
disable caching
@method disableCache;
*/
disableCache: function () {
this._sCache = null;
this._pCache = null;
this.singularize = function (word) {
return this._singularize(word);
};
this.pluralize = function (word) {
return this._pluralize(word);
};
},
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function (regex, string) {
if (this._cacheUsed) {
this.purgeCache();
}
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function (regex, string) {
if (this._cacheUsed) {
this.purgeCache();
}
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function (string) {
if (this._cacheUsed) {
this.purgeCache();
}
loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
if (this._cacheUsed) {
this.purgeCache();
}
loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function (word) {
return this._pluralize(word);
},
_pluralize: function (word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function (word) {
return this._singularize(word);
},
_singularize: function (word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function (word, typeRules, irregular) {
var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, rule, isUncountable;
isBlank = !word || BLANK_REGEX.test(word);
isCamelized = CAMELIZED_REGEX.test(word);
firstPhrase = "";
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word);
if (wordSplit) {
firstPhrase = wordSplit[1];
lastWord = wordSplit[2].toLowerCase();
}
isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord];
if (isUncountable) {
return word;
}
for (rule in irregular) {
if (lowercase.match(rule + "$")) {
substitution = irregular[rule];
if (isCamelized && irregular[lastWord]) {
substitution = capitalize(substitution);
rule = capitalize(rule);
}
return word.replace(new RegExp(rule, 'i'), substitution);
}
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i - 1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
exports.default = Inflector;
});
define('ember-inflector/lib/system/string', ['exports', 'ember-inflector/lib/system/inflector'], function (exports, _inflector) {
'use strict';
exports.__esModule = true;
exports.singularize = exports.pluralize = undefined;
function pluralize(word) {
return _inflector.default.inflector.pluralize(word);
}
function singularize(word) {
return _inflector.default.inflector.singularize(word);
}
exports.pluralize = pluralize;
exports.singularize = singularize;
});
define('ember-inflector/lib/utils/make-helper', ['exports', 'ember'], function (exports, _ember) {
'use strict';
exports.__esModule = true;
exports.default = makeHelper;
function makeHelper(helperFunction) {
if (_ember.default.Helper) {
return _ember.default.Helper.helper(helperFunction);
}
if (_ember.default.HTMLBars) {
return _ember.default.HTMLBars.makeBoundHelper(helperFunction);
}
return _ember.default.Handlebars.makeBoundHelper(helperFunction);
}
});
define('ember-load-initializers', ['exports'], function (exports) {
'use strict';
exports.__esModule = true;
exports.default = function (app, prefix) {
var initializerPrefix = prefix + '/initializers/';
var instanceInitializerPrefix = prefix + '/instance-initializers/';
var initializers = [];
var instanceInitializers = [];
// this is 2 pass because generally the first pass is the problem
// and is reduced, and resolveInitializer has potential to deopt
var moduleNames = Object.keys(requirejs._eak_seen);
for (var i = 0; i < moduleNames.length; i++) {
var moduleName = moduleNames[i];
if (moduleName.lastIndexOf(initializerPrefix, 0) === 0) {
initializers.push(moduleName);
} else if (moduleName.lastIndexOf(instanceInitializerPrefix, 0) === 0) {
instanceInitializers.push(moduleName);
}
}
registerInitializers(app, initializers);
registerInstanceInitializers(app, instanceInitializers);
};
function resolveInitializer(moduleName) {
var module = require(moduleName, null, null, true);
if (!module) {
throw new Error(moduleName + ' must export an initializer.');
}
var initializer = module['default'];
if (!initializer.name) {
initializer.name = moduleName.slice(moduleName.lastIndexOf('/') + 1);
}
return initializer;
}
function registerInitializers(app, moduleNames) {
for (var i = 0; i < moduleNames.length; i++) {
app.initializer(resolveInitializer(moduleNames[i]));
}
}
function registerInstanceInitializers(app, moduleNames) {
for (var i = 0; i < moduleNames.length; i++) {
app.instanceInitializer(resolveInitializer(moduleNames[i]));
}
}
});
define('ember', [], function() {
return {
default: Ember
};
});
require("ember-data");
require("ember-load-initializers")["default"](Ember.Application, "ember-data");
;(function() {
var global = require('ember-data/-private/global').default;
var DS = require('ember-data').default;
Object.defineProperty(global, 'DS', {
get: function() {
return DS;
}
});
})();
}).call(this);
;(function() {
function processEmberDataShims() {
var shims = {
'ember-data': { default: DS },
'ember-data/model': { default: DS.Model },
'ember-data/mixins/embedded-records': { default: DS.EmbeddedRecordsMixin },
'ember-data/serializers/rest': { default: DS.RESTSerializer },
'ember-data/serializers/active-model': { default: DS.ActiveModelSerializer },
'ember-data/serializers/json': { default: DS.JSONSerializer },
'ember-data/serializers/json-api': { default: DS.JSONAPISerializer },
'ember-data/serializer': { default: DS.Serializer },
'ember-data/adapters/json-api': { default: DS.JSONAPIAdapter },
'ember-data/adapters/rest': { default: DS.RESTAdapter },
'ember-data/adapter': { default: DS.Adapter },
'ember-data/adapters/active-model': { default: DS.ActiveModelAdapter },
'ember-data/store': { default: DS.Store },
'ember-data/transform': { default: DS.Transform },
'ember-data/attr': { default: DS.attr },
'ember-data/relationships': { hasMany: DS.hasMany, belongsTo: DS.belongsTo }
};
for (var moduleName in shims) {
generateModule(moduleName, shims[moduleName]);
}
}
function generateModule(name, values) {
define(name, [], function() {
'use strict';
return values;
});
}
if (typeof define !== 'undefined' && define && define.petal) {
processEmberDataShims();
}
})();
//# sourceMappingURL=ember-data.map
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js | dpoineau/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react'
import tiniestCat from './assets/tiniest-cat.jpg'
export default () => (
<img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" />
)
|
client/src/containers/Login.js | Nonsoft/crdweb | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { fetchLogin } from '../actions';
import LoginPage from '../components/pages/LoginPage';
class Login extends Component {
render() {
const { loginFailureInfo, fetchLogin } = this.props
return (
<LoginPage
handleSubmit={(username, password) => fetchLogin(username, password)}
loginFailureInfo={loginFailureInfo}
/>
);
}
}
Login.propTypes = {
loginFailureInfo: PropTypes.object,
fetchLogin: PropTypes.func.isRequired,
}
const mapStateToProps = (state) => {
return {
loginFailureInfo: state.loginFailureInfo,
}
}
const mapDispatchToProps = {
fetchLogin,
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
|
vendor/jquery/jquery.min.js | MaidaSt123/Examen- | /*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||(e=n.uniqueSort(e)),D.test(a)&&(e=e.reverse())),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=!0,c||j.disable(),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0;
}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),"object"!=typeof b&&"function"!=typeof b||(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}}),function(){var a;l.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,e;return c=d.getElementsByTagName("body")[0],c&&c.style?(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(d.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(e),a):void 0}}();var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),V=["Top","Right","Bottom","Left"],W=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function X(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&U.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var Y=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)Y(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";function ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={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:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/<tbody/i;function ia(a){Z.test(a.type)&&(a.defaultChecked=a.checked)}function ja(a,b,c,d,e){for(var f,g,h,i,j,k,m,o=a.length,p=ca(b),q=[],r=0;o>r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?"<table>"!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ma.test(f)?this.mouseHooks:la.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=g.srcElement||d),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,h.filter?h.filter(a,g):a},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button,h=b.fromElement;return null==a.pageX&&null!=b.clientX&&(e=a.target.ownerDocument||d,f=e.documentElement,c=e.body,a.pageX=b.clientX+(f&&f.scrollLeft||c&&c.scrollLeft||0)-(f&&f.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(f&&f.scrollTop||c&&c.scrollTop||0)-(f&&f.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&h&&(a.relatedTarget=h===a.target?b.toElement:h),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ra()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ra()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=d.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)}:function(a,b,c){var d="on"+b;a.detachEvent&&("undefined"==typeof a[d]&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?pa:qa):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:qa,isPropagationStopped:qa,isImmediatePropagationStopped:qa,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=pa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=pa,a&&!this.isSimulated&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=pa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submit||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?n.prop(b,"form"):void 0;c&&!n._data(c,"submit")&&(n.event.add(c,"submit._submit",function(a){a._submitBubble=!0}),n._data(c,"submit",!0))})},postDispatch:function(a){a._submitBubble&&(delete a._submitBubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.change||(n.event.special.change={setup:function(){return ka.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._justChanged=!0)}),n.event.add(this,"click._change",function(a){this._justChanged&&!a.isTrigger&&(this._justChanged=!1),n.event.simulate("change",this,a)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;ka.test(b.nodeName)&&!n._data(b,"change")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a)}),n._data(b,"change",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!ka.test(this.nodeName)}}),l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d){return sa(this,a,b,c,d)},one:function(a,b,c,d){return sa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=qa),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ta=/ jQuery\d+="(?:null|\d+)"/g,ua=new RegExp("<(?:"+ba+")[\\s/>]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/<script|<style|<link/i,xa=/checked\s*(?:[^=]|=\s*.checked.)/i,ya=/^true\/(.*)/,za=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ja[0].contentWindow||Ja[0].contentDocument).document,b.write(),b.close(),c=La(a,b),Ja.detach()),Ka[a]=c),c}var Na=/^margin/,Oa=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Pa=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Qa=d.documentElement;!function(){var b,c,e,f,g,h,i=d.createElement("div"),j=d.createElement("div");if(j.style){j.style.cssText="float:left;opacity:.5",l.opacity="0.5"===j.style.opacity,l.cssFloat=!!j.style.cssFloat,j.style.backgroundClip="content-box",j.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===j.style.backgroundClip,i=d.createElement("div"),i.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",j.innerHTML="",i.appendChild(j),l.boxSizing=""===j.style.boxSizing||""===j.style.MozBoxSizing||""===j.style.WebkitBoxSizing,n.extend(l,{reliableHiddenOffsets:function(){return null==b&&k(),f},boxSizingReliable:function(){return null==b&&k(),e},pixelMarginRight:function(){return null==b&&k(),c},pixelPosition:function(){return null==b&&k(),b},reliableMarginRight:function(){return null==b&&k(),g},reliableMarginLeft:function(){return null==b&&k(),h}});function k(){var k,l,m=d.documentElement;m.appendChild(i),j.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",b=e=h=!1,c=g=!0,a.getComputedStyle&&(l=a.getComputedStyle(j),b="1%"!==(l||{}).top,h="2px"===(l||{}).marginLeft,e="4px"===(l||{width:"4px"}).width,j.style.marginRight="50%",c="4px"===(l||{marginRight:"4px"}).marginRight,k=j.appendChild(d.createElement("div")),k.style.cssText=j.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",k.style.marginRight=k.style.width="0",j.style.width="1px",g=!parseFloat((a.getComputedStyle(k)||{}).marginRight),j.removeChild(k)),j.style.display="none",f=0===j.getClientRects().length,f&&(j.style.display="",j.innerHTML="<table><tr><td></td><td>t</td></tr></table>",j.childNodes[0].style.borderCollapse="separate",k=j.getElementsByTagName("td"),k[0].style.cssText="margin:0;border:0;padding:0;display:none",f=0===k[0].offsetHeight,f&&(k[0].style.display="",k[1].style.display="none",f=0===k[0].offsetHeight)),m.removeChild(i)}}}();var Ra,Sa,Ta=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ra=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Oa.test(g)&&Na.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0===g?g:g+""}):Qa.currentStyle&&(Ra=function(a){return a.currentStyle},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Oa.test(g)&&!Ta.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Ua(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Va=/alpha\([^)]*\)/i,Wa=/opacity\s*=\s*([^)]*)/i,Xa=/^(none|table(?!-c[ea]).+)/,Ya=new RegExp("^("+T+")(.*)$","i"),Za={position:"absolute",visibility:"hidden",display:"block"},$a={letterSpacing:"0",fontWeight:"400"},_a=["Webkit","O","Moz","ms"],ab=d.createElement("div").style;function bb(a){if(a in ab)return a;var b=a.charAt(0).toUpperCase()+a.slice(1),c=_a.length;while(c--)if(a=_a[c]+b,a in ab)return a}function cb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&W(d)&&(f[g]=n._data(d,"olddisplay",Ma(d.nodeName)))):(e=W(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function db(a,b,c){var d=Ya.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function eb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+V[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+V[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+V[f]+"Width",!0,e))):(g+=n.css(a,"padding"+V[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+V[f]+"Width",!0,e)));return g}function fb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ra(a),g=l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Sa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Oa.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+eb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Sa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=U.exec(c))&&e[1]&&(c=X(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Sa(a,b,d)),"normal"===f&&b in $a&&(f=$a[b]),""===c||c?(e=parseFloat(f),c===!0||isFinite(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Xa.test(n.css(a,"display"))&&0===a.offsetWidth?Pa(a,Za,function(){return fb(a,b,d)}):fb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ra(a);return db(a,c,d?eb(a,b,d,l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Wa.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Va,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Va.test(f)?f.replace(Va,e):f+" "+e)}}),n.cssHooks.marginRight=Ua(l.reliableMarginRight,function(a,b){return b?Pa(a,{display:"inline-block"},Sa,[a,"marginRight"]):void 0}),n.cssHooks.marginLeft=Ua(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Sa(a,"marginLeft"))||(n.contains(a.ownerDocument,a)?a.getBoundingClientRect().left-Pa(a,{
marginLeft:0},function(){return a.getBoundingClientRect().left}):0))+"px":void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+V[d]+b]=f[d]||f[d-2]||f[0];return e}},Na.test(a)||(n.cssHooks[a+b].set=db)}),n.fn.extend({css:function(a,b){return Y(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ra(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return cb(this,!0)},hide:function(){return cb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){W(this)?n(this).show():n(this).hide()})}});function gb(a,b,c,d,e){return new gb.prototype.init(a,b,c,d,e)}n.Tween=gb,gb.prototype={constructor:gb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=gb.propHooks[this.prop];return a&&a.get?a.get(this):gb.propHooks._default.get(this)},run:function(a){var b,c=gb.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):gb.propHooks._default.set(this),this}},gb.prototype.init.prototype=gb.prototype,gb.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},gb.propHooks.scrollTop=gb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=gb.prototype.init,n.fx.step={};var hb,ib,jb=/^(?:toggle|show|hide)$/,kb=/queueHooks$/;function lb(){return a.setTimeout(function(){hb=void 0}),hb=n.now()}function mb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=V[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function nb(a,b,c){for(var d,e=(qb.tweeners[b]||[]).concat(qb.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ob(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&W(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k="none"===j?n._data(a,"olddisplay")||Ma(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==Ma(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],jb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(o))"inline"===("none"===j?Ma(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=nb(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function pb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function qb(a,b,c){var d,e,f=0,g=qb.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=hb||lb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:hb||lb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(pb(k,j.opts.specialEasing);g>f;f++)if(d=qb.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,nb,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(qb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return X(c.elem,a,U.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],qb.tweeners[c]=qb.tweeners[c]||[],qb.tweeners[c].unshift(b)},prefilters:[ob],prefilter:function(a,b){b?qb.prefilters.unshift(a):qb.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(W).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=qb(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&kb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(mb(b,!0),a,d,e)}}),n.each({slideDown:mb("show"),slideUp:mb("hide"),slideToggle:mb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(hb=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),hb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ib||(ib=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(ib),ib=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a,b=d.createElement("input"),c=d.createElement("div"),e=d.createElement("select"),f=e.appendChild(d.createElement("option"));c=d.createElement("div"),c.setAttribute("className","t"),c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],b.setAttribute("type","checkbox"),c.appendChild(b),a=c.getElementsByTagName("a")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==c.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=f.selected,l.enctype=!!d.createElement("form").enctype,e.disabled=!0,l.optDisabled=!f.disabled,b=d.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value}();var rb=/\r/g,sb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(sb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>-1)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var tb,ub,vb=n.expr.attrHandle,wb=/^(?:checked|selected)$/i,xb=l.getSetAttribute,yb=l.input;n.fn.extend({attr:function(a,b){return Y(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ub:tb)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?yb&&xb||!wb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(xb?c:d)}}),ub={set:function(a,b,c){return b===!1?n.removeAttr(a,c):yb&&xb||!wb.test(c)?a.setAttribute(!xb&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=vb[b]||n.find.attr;yb&&xb||!wb.test(b)?vb[b]=function(a,b,d){var e,f;return d||(f=vb[b],vb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,vb[b]=f),e}:vb[b]=function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),yb&&xb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):tb&&tb.set(a,b,c)}}),xb||(tb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},vb.id=vb.name=vb.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:tb.set},n.attrHooks.contenteditable={set:function(a,b,c){tb.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var zb=/^(?:input|select|textarea|button|object)$/i,Ab=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return Y(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):zb.test(a.nodeName)||Ab.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var Bb=/[\t\r\n\f]/g;function Cb(a){return n.attr(a,"class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,Cb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,Cb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,Cb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=Cb(this),b&&n._data(this,"__className__",b),n.attr(this,"class",b||a===!1?"":n._data(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+Cb(c)+" ").replace(Bb," ").indexOf(b)>-1)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Db=a.location,Eb=n.now(),Fb=/\?/,Gb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(Gb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new a.DOMParser,c=d.parseFromString(b,"text/xml")):(c=new a.ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var Hb=/#.*$/,Ib=/([?&])_=[^&]*/,Jb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Kb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Lb=/^(?:GET|HEAD)$/,Mb=/^\/\//,Nb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ob={},Pb={},Qb="*/".concat("*"),Rb=Db.href,Sb=Nb.exec(Rb.toLowerCase())||[];function Tb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Ub(a,b,c,d){var e={},f=a===Pb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Vb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Wb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Xb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Rb,type:"GET",isLocal:Kb.test(Sb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Qb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Vb(Vb(a,n.ajaxSettings),b):Vb(n.ajaxSettings,a)},ajaxPrefilter:Tb(Ob),ajaxTransport:Tb(Pb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var d,e,f,g,h,i,j,k,l=n.ajaxSetup({},c),m=l.context||l,o=l.context&&(m.nodeType||m.jquery)?n(m):n.event,p=n.Deferred(),q=n.Callbacks("once memory"),r=l.statusCode||{},s={},t={},u=0,v="canceled",w={readyState:0,getResponseHeader:function(a){var b;if(2===u){if(!k){k={};while(b=Jb.exec(g))k[b[1].toLowerCase()]=b[2]}b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===u?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return u||(a=t[c]=t[c]||a,s[a]=b),this},overrideMimeType:function(a){return u||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>u)for(b in a)r[b]=[r[b],a[b]];else w.always(a[w.status]);return this},abort:function(a){var b=a||v;return j&&j.abort(b),y(0,b),this}};if(p.promise(w).complete=q.add,w.success=w.done,w.error=w.fail,l.url=((b||l.url||Rb)+"").replace(Hb,"").replace(Mb,Sb[1]+"//"),l.type=c.method||c.type||l.method||l.type,l.dataTypes=n.trim(l.dataType||"*").toLowerCase().match(G)||[""],null==l.crossDomain&&(d=Nb.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===Sb[1]&&d[2]===Sb[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(Sb[3]||("http:"===Sb[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=n.param(l.data,l.traditional)),Ub(Ob,l,c,w),2===u)return w;i=n.event&&l.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!Lb.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(Fb.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=Ib.test(f)?f.replace(Ib,"$1_="+Eb++):f+(Fb.test(f)?"&":"?")+"_="+Eb++)),l.ifModified&&(n.lastModified[f]&&w.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&w.setRequestHeader("If-None-Match",n.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Qb+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)w.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,w,l)===!1||2===u))return w.abort();v="abort";for(e in{success:1,error:1,complete:1})w[e](l[e]);if(j=Ub(Pb,l,c,w)){if(w.readyState=1,i&&o.trigger("ajaxSend",[w,l]),2===u)return w;l.async&&l.timeout>0&&(h=a.setTimeout(function(){w.abort("timeout")},l.timeout));try{u=1,j.send(s,y)}catch(x){if(!(2>u))throw x;y(-1,x)}}else y(-1,"No Transport");function y(b,c,d,e){var k,s,t,v,x,y=c;2!==u&&(u=2,h&&a.clearTimeout(h),j=void 0,g=e||"",w.readyState=b>0?4:0,k=b>=200&&300>b||304===b,d&&(v=Wb(l,w,d)),v=Xb(l,v,w,k),k?(l.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(n.lastModified[f]=x),x=w.getResponseHeader("etag"),x&&(n.etag[f]=x)),204===b||"HEAD"===l.type?y="nocontent":304===b?y="notmodified":(y=v.state,s=v.data,t=v.error,k=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),w.status=b,w.statusText=(c||y)+"",k?p.resolveWith(m,[s,y,w]):p.rejectWith(m,[w,y,t]),w.statusCode(r),r=void 0,i&&o.trigger(k?"ajaxSuccess":"ajaxError",[w,l,k?s:t]),q.fireWith(m,[w,y]),i&&(o.trigger("ajaxComplete",[w,l]),--n.active||n.event.trigger("ajaxStop")))}return w},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}});function Yb(a){return a.style&&a.style.display||n.css(a,"display")}function Zb(a){if(!n.contains(a.ownerDocument||d,a))return!0;while(a&&1===a.nodeType){if("none"===Yb(a)||"hidden"===a.type)return!0;a=a.parentNode}return!1}n.expr.filters.hidden=function(a){return l.reliableHiddenOffsets()?a.offsetWidth<=0&&a.offsetHeight<=0&&!a.getClientRects().length:Zb(a)},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var $b=/%20/g,_b=/\[\]$/,ac=/\r?\n/g,bc=/^(?:submit|button|image|reset|file)$/i,cc=/^(?:input|select|textarea|keygen)/i;function dc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||_b.test(a)?d(a,e):dc(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)dc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)dc(c,a[c],b,e);return d.join("&").replace($b,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&cc.test(this.nodeName)&&!bc.test(a)&&(this.checked||!Z.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(ac,"\r\n")}}):{name:b.name,value:c.replace(ac,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return this.isLocal?ic():d.documentMode>8?hc():/^(get|post|head|put|delete|options)$/i.test(this.type)&&hc()||ic()}:hc;var ec=0,fc={},gc=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in fc)fc[a](void 0,!0)}),l.cors=!!gc&&"withCredentials"in gc,gc=l.ajax=!!gc,gc&&n.ajaxTransport(function(b){if(!b.crossDomain||l.cors){var c;return{send:function(d,e){var f,g=b.xhr(),h=++ec;if(g.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(f in b.xhrFields)g[f]=b.xhrFields[f];b.mimeType&&g.overrideMimeType&&g.overrideMimeType(b.mimeType),b.crossDomain||d["X-Requested-With"]||(d["X-Requested-With"]="XMLHttpRequest");for(f in d)void 0!==d[f]&&g.setRequestHeader(f,d[f]+"");g.send(b.hasContent&&b.data||null),c=function(a,d){var f,i,j;if(c&&(d||4===g.readyState))if(delete fc[h],c=void 0,g.onreadystatechange=n.noop,d)4!==g.readyState&&g.abort();else{j={},f=g.status,"string"==typeof g.responseText&&(j.text=g.responseText);try{i=g.statusText}catch(k){i=""}f||!b.isLocal||b.crossDomain?1223===f&&(f=204):f=j.text?200:404}j&&e(f,i,j,g.getAllResponseHeaders())},b.async?4===g.readyState?a.setTimeout(c):g.onreadystatechange=fc[h]=c:c()},abort:function(){c&&c(void 0,!0)}}}});function hc(){try{return new a.XMLHttpRequest}catch(b){}}function ic(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=d.head||n("head")[0]||d.documentElement;return{send:function(e,f){b=d.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||f(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var jc=[],kc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=jc.pop()||n.expando+"_"+Eb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(kc.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&kc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(kc,"$1"+e):b.jsonp!==!1&&(b.url+=(Fb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,jc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ja([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var lc=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&lc)return lc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h,a.length)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function mc(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?("undefined"!=typeof e.getBoundingClientRect&&(d=e.getBoundingClientRect()),c=mc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Qa})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return Y(this,function(a,d,e){var f=mc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ua(l.pixelPosition,function(a,c){return c?(c=Sa(a,b),Oa.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({
padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return Y(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var nc=a.jQuery,oc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=oc),b&&a.jQuery===n&&(a.jQuery=nc),n},b||(a.jQuery=a.$=n),n});
|
client/controller/common.js | yeoh-joer/synapse | /**
* External dependencies
*/
import React from 'react'
import { noop } from 'lodash'
/**
* Internal dependencies
*/
import { setFragment as setFragmentAction } from 'client/state/ui/actions'
import { getCurrentUser } from 'client/state/current-user/selectors'
export function makeLayoutMiddleware(LayoutComponent) {
return function (ctx, next) {
const { store, primary, secondary } = ctx
// On server, only render LoggedOutLayout when logged-out
if (! ctx.isServerSide || ! getCurrentUser(store.getState())) {
let redirectUri
if (ctx.isServerSide) {
redirectUri = `${ctx.protocol}://${ctx.host}${ctx.originalUrl}`
}
ctx.layout = (
<LayoutComponent
store={ store }
primary={ primary }
secondary={ secondary }
/>
)
}
next()
}
}
export function setFragment(fragment) {
return function (ctx, next = noop) {
ctx.store.dispatch(setFragmentAction(fragment))
next()
}
}
|
src/parser/deathknight/blood/modules/features/MarrowrendUsage.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import Analyzer from 'parser/core/Analyzer';
const REFRESH_AT_STACKS_WITH_BONES_OF_THE_DAMNED = 6;
const REFRESH_AT_STACKS_WITHOUT_BONES_OF_THE_DAMNED = 7;
const REFRESH_AT_SECONDS = 6;
const BS_DURATION = 30;
const MR_GAIN = 3;
class MarrowrendUsage extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
/*
currentBoneShieldBuffer contains the BS stacks caused by the actual MR cast
since the applyBuffStack event happens before the cast event
*/
currentBoneShieldStacks = 0;
currentBoneShieldBuffer = 0;
lastMarrowrendCast = 0;
bsStacksWasted = 0;
botdStacksWasted = 0;
refreshMRCasts = 0;
totalMRCasts = 0;
badMRCasts = 0;
hasBonesOfTheDamned = false;
refreshAtStacks = REFRESH_AT_STACKS_WITHOUT_BONES_OF_THE_DAMNED; // contains number for the tooltip for proper MR-usage, not used for calculations
bonesOfTheDamnedProc = 0;
totalStacksGenerated = 0;
constructor(...args) {
super(...args);
if(this.selectedCombatant.hasTrait(SPELLS.BONES_OF_THE_DAMNED.id)) {
this.hasBonesOfTheDamned = true;
this.refreshAtStacks = REFRESH_AT_STACKS_WITH_BONES_OF_THE_DAMNED;
}
}
on_toPlayer_applybuff(event) {
if (event.ability.guid === SPELLS.BONE_SHIELD.id){
this.currentBoneShieldBuffer += 1;
this.currentBoneShieldStacks = event.stack;
}
}
on_toPlayer_applybuffstack(event) {
if (event.ability.guid === SPELLS.BONE_SHIELD.id){
this.currentBoneShieldBuffer += 1;
this.currentBoneShieldStacks = event.stack;
}
}
on_toPlayer_removebuff(event) {
if (event.ability.guid === SPELLS.BONE_SHIELD.id){
this.currentBoneShieldStacks = 0;
}
}
on_toPlayer_removebuffstack(event) {
if (event.ability.guid === SPELLS.BONE_SHIELD.id){
this.currentBoneShieldBuffer = 0;
this.currentBoneShieldStacks = event.stack;
}
}
on_byPlayer_cast(event) {
if (event.ability.guid !== SPELLS.MARROWREND.id) return;
//don't add to wasted casts if MR casts was at ~6sec left on BS duration
const durationLeft = BS_DURATION - (event.timestamp - this.lastMarrowrendCast) / 1000;
if (durationLeft <= REFRESH_AT_SECONDS) {
this.refreshMRCasts += 1;
} else {
const boneShieldStacks = this.currentBoneShieldStacks - this.currentBoneShieldBuffer;
let badCast = '';
if (boneShieldStacks > REFRESH_AT_STACKS_WITHOUT_BONES_OF_THE_DAMNED) {
// this was a wasted charge for sure
const wasted = MR_GAIN - this.currentBoneShieldBuffer;
this.badMRCasts += 1;
this.bsStacksWasted += wasted;
badCast = badCast + `You made this cast with ${boneShieldStacks} stacks of Bone Shield while it had ${(durationLeft).toFixed(1)} seconds left, wasting ${wasted} charges.`;
}
if (this.hasBonesOfTheDamned && boneShieldStacks >= REFRESH_AT_STACKS_WITHOUT_BONES_OF_THE_DAMNED) {
// this was a potentially proc of BotD
this.botdStacksWasted += 1;
badCast = badCast + `This cast couldn't proc ${SPELLS.BONES_OF_THE_DAMNED.name} because you had already ${boneShieldStacks} stacks.`;
}
if (badCast !== '') {
event.meta = event.meta || {};
event.meta.isInefficientCast = true;
event.meta.inefficientCastReason = badCast;
}
}
if (this.currentBoneShieldBuffer > MR_GAIN && this.hasBonesOfTheDamned) {
// count Bones of the Damned procs and mark cast in timeline
event.meta = event.meta || {};
event.meta.isEnhancedCast = true;
event.meta.enhancedCastReason = `This ${SPELLS.MARROWREND.name} cast procced ${SPELLS.BONES_OF_THE_DAMNED.name}`;
this.bonesOfTheDamnedProc += 1;
}
this.totalStacksGenerated += this.currentBoneShieldBuffer;
this.currentBoneShieldBuffer = 0;
this.lastMarrowrendCast = event.timestamp;
this.totalMRCasts += 1;
}
get bonesOfTheDamnedProcs() {
return this.bonesOfTheDamnedProc;
}
get wastedbonesOfTheDamnedProcs() {
return this.botdStacksWasted;
}
get totalBoneShieldStacksGenerated() {
return this.totalStacksGenerated;
}
get wastedBoneShieldStacksPercent() {
return this.bsStacksWasted / (this.totalStacksGenerated + this.bsStacksWasted);
}
get marrowrendCasts() {
return this.totalMRCasts;
}
get refreshWithStacks() {
return this.refreshAtStacks;
}
get suggestionThresholds() {
return {
actual: this.wastedBoneShieldStacksPercent,
isGreaterThan: {
minor: 0,
average: 0.1,
major: .2,
},
style: 'percentage',
};
}
get suggestionThresholdsEfficiency() {
return {
actual: 1 - this.wastedBoneShieldStacksPercent,
isLessThan: {
minor: 1,
average: 0.9,
major: .8,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
const botDDisclaimer = this.hasBonesOfTheDamned ? ` (not counting possible ${SPELLS.BONES_OF_THE_DAMNED.name} procs)` : '';
return suggest(<>You casted {this.badMRCasts} Marrowrends with more than {REFRESH_AT_STACKS_WITHOUT_BONES_OF_THE_DAMNED} stacks of <SpellLink id={SPELLS.BONE_SHIELD.id} /> that were not about to expire, wasting {this.bsStacksWasted} stacks{botDDisclaimer}.<br />Cast <SpellLink id={SPELLS.HEART_STRIKE.id} /> instead if you are at {this.refreshAtStacks} stacks or above.</>)
.icon(SPELLS.MARROWREND.icon)
.actual(`${formatPercentage(actual)}% wasted ${SPELLS.BONE_SHIELD.name} stacks`)
.recommended(`${this.bsStacksWasted} stacks wasted, ${this.totalStacksGenerated} stacks generated`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.MARROWREND.id} />}
value={`${this.badMRCasts} / ${this.totalMRCasts}`}
label="Bad Marrowrend casts"
tooltip={(
<>
{this.refreshMRCasts} casts to refresh Bone Shield, those do not count towards bad casts.<br />
{this.hasBonesOfTheDamned && <>{this.wastedbonesOfTheDamnedProcs} casts with {REFRESH_AT_STACKS_WITHOUT_BONES_OF_THE_DAMNED} stacks of {SPELLS.BONE_SHIELD.name}, wasting potential {SPELLS.BONES_OF_THE_DAMNED.name} procs.<br /></>}
{this.badMRCasts} casts with more than {REFRESH_AT_STACKS_WITHOUT_BONES_OF_THE_DAMNED} stacks of Bone Shield wasting {this.bsStacksWasted} stacks.<br /><br />
Avoid casting Marrowrend unless you have {this.refreshAtStacks} or less stacks or if Bone Shield has less than 6sec of its duration left.
</>
)}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(3);
}
export default MarrowrendUsage;
|
ajax/libs/videomail-client/1.27.9/videomail-client.js | maruilian11/cdnjs | require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var EventEmitter = require('events').EventEmitter,
inherits = require('inherits'),
raf = require('raf'),
methods;
//the same as off window unless polyfilled or in node
var defaultRAFObject = {
requestAnimationFrame: raf,
cancelAnimationFrame: raf.cancel
};
function returnTrue(){ return true; }
//manage FPS if < 60, else return true;
function makeThrottle(fps){
var delay = 1000/fps;
var lastTime = Date.now();
if( fps<=0 || fps === Infinity ){
return returnTrue;
}
//if an fps throttle has been set then we'll assume
//it natively runs at 60fps,
var half = Math.ceil(1000 / 60) / 2;
return function(){
//if a custom fps is requested
var now = Date.now();
//is this frame within 8.5ms of the target?
//if so then next frame is gonna be too late
if(now - lastTime < delay - half){
return false;
}
lastTime = now;
return true;
};
}
/**
* Animitter provides event-based loops for the browser and node,
* using `requestAnimationFrame`
* @param {Object} [opts]
* @param {Number} [opts.fps=Infinity] the framerate requested, defaults to as fast as it can (60fps on window)
* @param {Number} [opts.delay=0] milliseconds delay between invoking `start` and initializing the loop
* @param {Object} [opts.requestAnimationFrameObject=global] the object on which to find `requestAnimationFrame` and `cancelAnimationFrame` methods
* @param {Boolean} [opts.fixedDelta=false] if true, timestamps will pretend to be executed at fixed intervals always
* @constructor
*/
function Animitter( opts ){
opts = opts || {};
this.__delay = opts.delay || 0;
/** @expose */
this.fixedDelta = !!opts.fixedDelta;
/** @expose */
this.frameCount = 0;
/** @expose */
this.deltaTime = 0;
/** @expose */
this.elapsedTime = 0;
/** @private */
this.__running = false;
/** @private */
this.__completed = false;
this.setFPS(opts.fps || Infinity);
this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject);
}
inherits(Animitter, EventEmitter);
function onStart(scope){
var now = Date.now();
var rAFID;
//dont let a second animation start on the same object
//use *.on('update',fn)* instead
if(scope.__running){
return scope;
}
exports.running += 1;
scope.__running = true;
scope.__lastTime = now;
scope.deltaTime = 0;
//emit **start** once at the beginning
scope.emit('start', scope.deltaTime, 0, scope.frameCount);
var lastRAFObject = scope.requestAnimationFrameObject;
var drawFrame = function(){
if(lastRAFObject !== scope.requestAnimationFrameObject){
//if the requestAnimationFrameObject switched in-between,
//then re-request with the new one to ensure proper update execution context
//i.e. VRDisplay#submitFrame() may only be requested through VRDisplay#requestAnimationFrame(drawFrame)
lastRAFObject = scope.requestAnimationFrameObject;
scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame);
return;
}
if(scope.__isReadyForUpdate()){
scope.update();
}
if(scope.__running){
rAFID = scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame);
} else {
scope.requestAnimationFrameObject.cancelAnimationFrame(rAFID);
}
};
scope.requestAnimationFrameObject.requestAnimationFrame(drawFrame);
return scope;
}
methods = {
//EventEmitter Aliases
off : EventEmitter.prototype.removeListener,
trigger : EventEmitter.prototype.emit,
/**
* stops the animation and marks it as completed
* @emit Animitter#complete
* @returns {Animitter}
*/
complete: function(){
this.stop();
this.__completed = true;
this.emit('complete', this.frameCount, this.deltaTime);
return this;
},
/**
* stops the animation and removes all listeners
* @emit Animitter#stop
* @returns {Animitter}
*/
dispose: function(){
this.stop();
this.removeAllListeners();
return this;
},
/**
* get milliseconds between the last 2 updates
*
* @return {Number}
*/
getDeltaTime: function(){
return this.deltaTime;
},
/**
* get the total milliseconds that the animation has ran.
* This is the cumlative value of the deltaTime between frames
*
* @return {Number}
*/
getElapsedTime: function(){
return this.elapsedTime;
},
/**
* get the instances frames per second as calculated by the last delta
*
* @return {Number}
*/
getFPS: function(){
return this.deltaTime > 0 ? 1000 / this.deltaTime : 0;
if(this.deltaTime){
return 1000 / this.deltaTime;
}
},
/**
* get the explicit FPS limit set via `Animitter#setFPS(fps)` or
* via the initial `options.fps` property
*
* @returns {Number} either as set or Infinity
*/
getFPSLimit: function(){
return this.__fps;
},
/**
* get the number of frames that have occurred
*
* @return {Number}
*/
getFrameCount: function(){
return this.frameCount;
},
/**
* get the object providing `requestAnimationFrame`
* and `cancelAnimationFrame` methods
* @return {Object}
*/
getRequestAnimationFrameObject: function(){
return this.requestAnimationFrameObject;
},
/**
* is the animation loop active
*
* @return {boolean}
*/
isRunning: function(){
return this.__running;
},
/**
* is the animation marked as completed
*
* @return {boolean}
*/
isCompleted: function(){
return this.__completed;
},
/**
* reset the animation loop, marks as incomplete,
* leaves listeners intact
*
* @emit Animitter#reset
* @return {Animitter}
*/
reset: function(){
this.stop();
this.__completed = false;
this.__lastTime = 0;
this.deltaTime = 0;
this.elapsedTime = 0;
this.frameCount = 0;
this.emit('reset', 0, 0, this.frameCount);
return this;
},
/**
* set the framerate for the animation loop
*
* @param {Number} fps
* @return {Animitter}
*/
setFPS: function(fps){
this.__fps = fps;
this.__isReadyForUpdate = makeThrottle(fps);
return this;
},
/**
* set the object that will provide `requestAnimationFrame`
* and `cancelAnimationFrame` methods to this instance
* @param {Object} object
* @return {Animitter}
*/
setRequestAnimationFrameObject: function(object){
if(typeof object.requestAnimationFrame !== 'function' || typeof object.cancelAnimationFrame !== 'function'){
throw new Error("Invalid object provide to `setRequestAnimationFrameObject`");
}
this.requestAnimationFrameObject = object;
return this;
},
/**
* start an animation loop
* @emit Animitter#start
* @return {Animitter}
*/
start: function(){
var self = this;
if(this.__delay){
setTimeout(function(){
onStart(self);
}, this.__delay);
} else {
onStart(this);
}
return this;
},
/**
* stops the animation loop, does not mark as completed
*
* @emit Animitter#stop
* @return {Animitter}
*/
stop: function(){
if( this.__running ){
this.__running = false;
exports.running -= 1;
this.emit('stop', this.deltaTime, this.elapsedTime, this.frameCount);
}
return this;
},
/**
* update the animation loop once
*
* @emit Animitter#update
* @return {Animitter}
*/
update: function(){
this.frameCount++;
/** @private */
var now = Date.now();
this.__lastTime = this.__lastTime || now;
this.deltaTime = (this.fixedDelta || exports.globalFixedDelta) ? 1000/Math.min(60, this.__fps) : now - this.__lastTime;
this.elapsedTime += this.deltaTime;
this.__lastTime = now;
this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount);
return this;
}
};
for(var method in methods){
Animitter.prototype[method] = methods[method];
}
/**
* create an animitter instance,
* @param {Object} [options]
* @param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number )
* @returns {Animitter}
*/
function createAnimitter(options, fn){
if( arguments.length === 1 && typeof options === 'function'){
fn = options;
options = {};
}
var _instance = new Animitter( options );
if( fn ){
_instance.on('update', fn);
}
return _instance;
}
module.exports = exports = createAnimitter;
/**
* create an animitter instance,
* where the scope is bound in all functions
* @param {Object} [options]
* @param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number )
* @returns {Animitter}
*/
exports.bound = function(options, fn){
var loop = createAnimitter(options, fn),
functionKeys = functions(Animitter.prototype),
hasBind = !!Function.prototype.bind,
fnKey;
for(var i=0; i<functionKeys.length; i++){
fnKey = functionKeys[i];
loop[fnKey] = hasBind ? loop[fnKey].bind(loop) : bind(loop[fnKey], loop);
}
return loop;
};
exports.Animitter = Animitter;
/**
* if true, all `Animitter` instances will behave as if `options.fixedDelta = true`
*/
exports.globalFixedDelta = false;
//helpful to inherit from when using bundled
exports.EventEmitter = EventEmitter;
//keep a global counter of all loops running, helpful to watch in dev tools
exports.running = 0;
function bind(fn, scope){
if(typeof fn.bind === 'function'){
return fn.bind(scope);
}
return function(){
return fn.apply(scope, arguments);
};
}
function functions(obj){
var keys = Object.keys(obj);
var arr = [];
for(var i=0; i<keys.length; i++){
if(typeof obj[keys[i]] === 'function'){
arr.push(keys[i]);
}
}
return arr;
}
//polyfill Date.now for real-old browsers
Date.now = Date.now || function now() {
return new Date().getTime();
};
},{"events":314,"inherits":325,"raf":340}],2:[function(require,module,exports){
var toBuffer = require('typedarray-to-buffer'),
isFloat32Array = require('validate.io-float32array')
module.exports = function(float32Array) {
if (!float32Array)
throw new Error('A Float32Array parameter is missing.')
if (!isFloat32Array(float32Array))
throw new Error('The parameter is not a Float32Array.')
this.toBuffer = function() {
var l = float32Array.length,
arr = new Int16Array(l),
i
for (i = 0; i < l; i++) {
arr[i] = Math.min(1, float32Array[i]) * 0x7FFF
}
return toBuffer(arr)
}
}
},{"typedarray-to-buffer":363,"validate.io-float32array":369}],3:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],4:[function(require,module,exports){
},{}],5:[function(require,module,exports){
/*!
* Cross-Browser Split 1.1.1
* Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
* Available under the MIT License
* ECMAScript compliant, uniform cross-browser split method
*/
/**
* Splits a string into an array of strings using a regex or string separator. Matches of the
* separator are not included in the result array. However, if `separator` is a regex that contains
* capturing groups, backreferences are spliced into the result each time `separator` is matched.
* Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
* cross-browser.
* @param {String} str String to split.
* @param {RegExp|String} separator Regex or string to use for separating the string.
* @param {Number} [limit] Maximum number of items to include in the result array.
* @returns {Array} Array of substrings.
* @example
*
* // Basic use
* split('a b c d', ' ');
* // -> ['a', 'b', 'c', 'd']
*
* // With limit
* split('a b c d', ' ', 2);
* // -> ['a', 'b']
*
* // Backreferences in result array
* split('..word1 word2..', /([a-z]+)(\d+)/i);
* // -> ['..', 'word', '1', ' ', 'word', '2', '..']
*/
module.exports = (function split(undef) {
var nativeSplit = String.prototype.split,
compliantExecNpcg = /()??/.exec("")[1] === undef,
// NPCG: nonparticipating capturing group
self;
self = function(str, separator, limit) {
// If `separator` is not a regex, use `nativeSplit`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return nativeSplit.call(str, separator, limit);
}
var output = [],
flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
(separator.sticky ? "y" : ""),
// Firefox 3+
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
separator = new RegExp(separator.source, flags + "g"),
separator2, match, lastIndex, lastLength;
str += ""; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // Math.pow(2, 32) - 1
* If 0, Infinity, or NaN: 0
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
* If other: Type-convert, then use the above rules
*/
limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1
limit >>> 0; // ToUint32(limit)
while (match = separator.exec(str)) {
// `separator.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0].length;
if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function() {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undef) {
match[i] = undef;
}
}
});
}
if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // Avoid an infinite loop
}
}
if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
return self;
})();
},{}],6:[function(require,module,exports){
(function (global){
'use strict';
var buffer = require('buffer');
var Buffer = buffer.Buffer;
var SlowBuffer = buffer.SlowBuffer;
var MAX_LEN = buffer.kMaxLength || 2147483647;
exports.alloc = function alloc(size, fill, encoding) {
if (typeof Buffer.alloc === 'function') {
return Buffer.alloc(size, fill, encoding);
}
if (typeof encoding === 'number') {
throw new TypeError('encoding must not be number');
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
var enc = encoding;
var _fill = fill;
if (_fill === undefined) {
enc = undefined;
_fill = 0;
}
var buf = new Buffer(size);
if (typeof _fill === 'string') {
var fillBuf = new Buffer(_fill, enc);
var flen = fillBuf.length;
var i = -1;
while (++i < size) {
buf[i] = fillBuf[i % flen];
}
} else {
buf.fill(_fill);
}
return buf;
}
exports.allocUnsafe = function allocUnsafe(size) {
if (typeof Buffer.allocUnsafe === 'function') {
return Buffer.allocUnsafe(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
return new Buffer(size);
}
exports.from = function from(value, encodingOrOffset, length) {
if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
return Buffer.from(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (typeof value === 'string') {
return new Buffer(value, encodingOrOffset);
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
var offset = encodingOrOffset;
if (arguments.length === 1) {
return new Buffer(value);
}
if (typeof offset === 'undefined') {
offset = 0;
}
var len = length;
if (typeof len === 'undefined') {
len = value.byteLength - offset;
}
if (offset >= value.byteLength) {
throw new RangeError('\'offset\' is out of bounds');
}
if (len > value.byteLength - offset) {
throw new RangeError('\'length\' is out of bounds');
}
return new Buffer(value.slice(offset, offset + len));
}
if (Buffer.isBuffer(value)) {
var out = new Buffer(value.length);
value.copy(out, 0, 0, value.length);
return out;
}
if (value) {
if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
return new Buffer(value);
}
if (value.type === 'Buffer' && Array.isArray(value.data)) {
return new Buffer(value.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
}
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
if (typeof Buffer.allocUnsafeSlow === 'function') {
return Buffer.allocUnsafeSlow(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size >= MAX_LEN) {
throw new RangeError('size is too large');
}
return new SlowBuffer(size);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"buffer":7}],7:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (value instanceof ArrayBuffer) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: new Buffer(val, encoding)
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView (obj) {
return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
}
function numberIsNaN (obj) {
return obj !== obj // eslint-disable-line no-self-compare
}
},{"base64-js":3,"ieee754":323}],8:[function(require,module,exports){
var toBuffer = require('typedarray-to-buffer'),
isBrowser = typeof(document) !== 'undefined' && typeof(document.createElement) === 'function',
// cached, used only once for browser environments
verifiedImageType
module.exports = function(canvas, options) {
var self = this, quality
options = options ? options : {}
options.image = options.image ? options.image : {}
options.image.types = options.image.types ? options.image.types : []
// validate some options this class needs
if (options.image.types.length > 2)
throw new Error('Too many image types are specified!')
else if (options.image.types.length < 1) {
// Set a default image type, just to be robust
options.image.types = isBrowser ? ['webp', 'jpeg'] : ['png']
}
if (!options.image.quality)
options.image.quality = .5 // default
quality = parseFloat(options.image.quality)
function composeImageType(index) {
var imageType
if (options.image.types[index])
imageType = 'image/' + options.image.types[index]
return imageType
}
function isMatch(uri, imageType) {
var match = uri && uri.match(imageType)
match && options.debug && options.debug('Image type %s verified', imageType)
return match
}
// Performance tweak, we do not need a big canvas for finding out the supported image type
function getTestCanvas() {
var testCanvas
if (isBrowser) {
testCanvas = document.createElement('canvas')
testCanvas.width = testCanvas.height = 1
} else
testCanvas = canvas
return testCanvas
}
function canvasSupportsImageTypeAsync(imageType, cb) {
try {
getTestCanvas().toDataURL(imageType, function(err, uri) {
if (err)
cb(err)
else
cb(null, isMatch(uri, imageType))
})
} catch (exc) {
cb(null, false)
}
}
function canvasSupportsImageTypeSync(imageType) {
var match
try {
var testCanvas = getTestCanvas(),
uri = testCanvas.toDataURL && testCanvas.toDataURL(imageType)
match = isMatch(uri, imageType)
} catch (exc) {
// Can happen when i.E. a spider is coming. Just be robust here and continue.
options.debug &&
options.logger.debug('Failed to call toDataURL() on canvas for image type %s', imageType)
}
return match
}
function verifyImageTypeAsync(imageType, cb) {
canvasSupportsImageTypeAsync(imageType, function(err, match) {
if (err)
cb(err)
else {
if (match)
cb(null, imageType)
else {
imageType = composeImageType(1)
canvasSupportsImageTypeAsync(imageType, function(err, match) {
if (err)
cb(err)
else
cb(null, match ? imageType: null)
})
}
}
})
}
function verifyImageTypeSync(imageType) {
if (!canvasSupportsImageTypeSync(imageType)) {
if (options.image.types[1]) {
imageType = composeImageType(1)
if (!canvasSupportsImageTypeSync(imageType))
imageType = null
} else
imageType = null
}
!imageType && options.debug && options.logger.debug('Unable to verify image type')
return imageType
}
// callbacks are needed for server side tests
function verifyImageType(cb) {
var imageType = composeImageType(0)
if (cb) {
verifyImageTypeAsync(imageType, cb)
} else {
return verifyImageTypeSync(imageType)
}
}
// this method is proven to be fast, see
// http://jsperf.com/data-uri-to-buffer-performance/3
function uriToBuffer(uri) {
var uri = uri.split(',')[1],
bytes
// Beware that the atob function might be a static one for server side tests
if (typeof(atob) === 'function')
bytes = atob(uri)
else if (typeof(self.constructor.atob) === 'function')
bytes = self.constructor.atob(uri)
else
throw new Error('atob function is missing')
var arr = new Uint8Array(bytes.length)
// http://mrale.ph/blog/2014/12/24/array-length-caching.html
for (var i = 0, l = bytes.length; i < l; i++) {
arr[i] = bytes.charCodeAt(i)
}
return toBuffer(arr)
}
function toBufferSync() {
var imageType = self.getImageType(),
buffer
if (imageType) {
var uri = canvas.toDataURL(imageType, quality)
buffer = uriToBuffer(uri)
}
return buffer
}
function toBufferAsync(cb) {
self.getImageType(function(err, imageType) {
if (err)
cb(err)
else if (!imageType)
cb()
else
canvas.toDataURL(imageType, function(err, uri) {
if (err)
cb(err)
else
cb(null, uriToBuffer(uri))
})
})
}
this.toBuffer = function(cb) {
if (cb)
toBufferAsync(cb)
else
return toBufferSync()
}
// browsers do not need a callback, but tests do
this.getImageType = function(cb) {
// only run for the first time this constructor is called and
// cache result for the next calls
if (cb) {
if (!verifiedImageType || !isBrowser)
verifyImageType(function(err, newVerifiedImageType) {
if (err)
cb(err)
else {
verifiedImageType = newVerifiedImageType
cb(null, verifiedImageType)
}
})
else
cb(null, verifiedImageType)
} else {
// on the browser side we do cache it for speed
if (!verifiedImageType || !isBrowser)
verifiedImageType = verifyImageType()
return verifiedImageType
}
}
}
},{"typedarray-to-buffer":363}],9:[function(require,module,exports){
// contains, add, remove, toggle
var indexof = require('indexof')
module.exports = ClassList
function ClassList(elem) {
var cl = elem.classList
if (cl) {
return cl
}
var classList = {
add: add
, remove: remove
, contains: contains
, toggle: toggle
, toString: $toString
, length: 0
, item: item
}
return classList
function add(token) {
var list = getTokens()
if (indexof(list, token) > -1) {
return
}
list.push(token)
setTokens(list)
}
function remove(token) {
var list = getTokens()
, index = indexof(list, token)
if (index === -1) {
return
}
list.splice(index, 1)
setTokens(list)
}
function contains(token) {
return indexof(getTokens(), token) > -1
}
function toggle(token) {
if (contains(token)) {
remove(token)
return false
} else {
add(token)
return true
}
}
function $toString() {
return elem.className
}
function item(index) {
var tokens = getTokens()
return tokens[index] || null
}
function getTokens() {
var className = elem.className
return filter(className.split(" "), isTruthy)
}
function setTokens(list) {
var length = list.length
elem.className = list.join(" ")
classList.length = length
for (var i = 0; i < list.length; i++) {
classList[i] = list[i]
}
delete list[length]
}
}
function filter (arr, fn) {
var ret = []
for (var i = 0; i < arr.length; i++) {
if (fn(arr[i])) ret.push(arr[i])
}
return ret
}
function isTruthy(value) {
return !!value
}
},{"indexof":324}],10:[function(require,module,exports){
/*
* classList.js: Cross-browser full element.classList implementation.
* 1.1.20150312
*
* By Eli Grey, http://eligrey.com
* License: Dedicated to the public domain.
* See https://github.com/eligrey/classList.js/blob/master/LICENSE.md
*/
/*global self, document, DOMException */
/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */
if ("document" in self) {
// Full polyfill for browsers with no classList support
// Including IE < Edge missing SVGElement.classList
if (!("classList" in document.createElement("_"))
|| document.createElementNS && !("classList" in document.createElementNS("http://www.w3.org/2000/svg","g"))) {
(function (view) {
"use strict";
if (!('Element' in view)) return;
var
classListProp = "classList"
, protoProp = "prototype"
, elemCtrProto = view.Element[protoProp]
, objCtr = Object
, strTrim = String[protoProp].trim || function () {
return this.replace(/^\s+|\s+$/g, "");
}
, arrIndexOf = Array[protoProp].indexOf || function (item) {
var
i = 0
, len = this.length
;
for (; i < len; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
}
// Vendors: please allow content code to instantiate DOMExceptions
, DOMEx = function (type, message) {
this.name = type;
this.code = DOMException[type];
this.message = message;
}
, checkTokenAndGetIndex = function (classList, token) {
if (token === "") {
throw new DOMEx(
"SYNTAX_ERR"
, "An invalid or illegal string was specified"
);
}
if (/\s/.test(token)) {
throw new DOMEx(
"INVALID_CHARACTER_ERR"
, "String contains an invalid character"
);
}
return arrIndexOf.call(classList, token);
}
, ClassList = function (elem) {
var
trimmedClasses = strTrim.call(elem.getAttribute("class") || "")
, classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
, i = 0
, len = classes.length
;
for (; i < len; i++) {
this.push(classes[i]);
}
this._updateClassName = function () {
elem.setAttribute("class", this.toString());
};
}
, classListProto = ClassList[protoProp] = []
, classListGetter = function () {
return new ClassList(this);
}
;
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error's toString() is sufficient here.
DOMEx[protoProp] = Error[protoProp];
classListProto.item = function (i) {
return this[i] || null;
};
classListProto.contains = function (token) {
token += "";
return checkTokenAndGetIndex(this, token) !== -1;
};
classListProto.add = function () {
var
tokens = arguments
, i = 0
, l = tokens.length
, token
, updated = false
;
do {
token = tokens[i] + "";
if (checkTokenAndGetIndex(this, token) === -1) {
this.push(token);
updated = true;
}
}
while (++i < l);
if (updated) {
this._updateClassName();
}
};
classListProto.remove = function () {
var
tokens = arguments
, i = 0
, l = tokens.length
, token
, updated = false
, index
;
do {
token = tokens[i] + "";
index = checkTokenAndGetIndex(this, token);
while (index !== -1) {
this.splice(index, 1);
updated = true;
index = checkTokenAndGetIndex(this, token);
}
}
while (++i < l);
if (updated) {
this._updateClassName();
}
};
classListProto.toggle = function (token, force) {
token += "";
var
result = this.contains(token)
, method = result ?
force !== true && "remove"
:
force !== false && "add"
;
if (method) {
this[method](token);
}
if (force === true || force === false) {
return force;
} else {
return !result;
}
};
classListProto.toString = function () {
return this.join(" ");
};
if (objCtr.defineProperty) {
var classListPropDesc = {
get: classListGetter
, enumerable: true
, configurable: true
};
try {
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
} catch (ex) { // IE 8 doesn't support enumerable:true
if (ex.number === -0x7FF5EC54) {
classListPropDesc.enumerable = false;
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
}
}
} else if (objCtr[protoProp].__defineGetter__) {
elemCtrProto.__defineGetter__(classListProp, classListGetter);
}
}(self));
} else {
// There is full or partial native classList support, so just check if we need
// to normalize the add/remove and toggle APIs.
(function () {
"use strict";
var testElement = document.createElement("_");
testElement.classList.add("c1", "c2");
// Polyfill for IE 10/11 and Firefox <26, where classList.add and
// classList.remove exist but support only one argument at a time.
if (!testElement.classList.contains("c2")) {
var createMethod = function(method) {
var original = DOMTokenList.prototype[method];
DOMTokenList.prototype[method] = function(token) {
var i, len = arguments.length;
for (i = 0; i < len; i++) {
token = arguments[i];
original.call(this, token);
}
};
};
createMethod('add');
createMethod('remove');
}
testElement.classList.toggle("c3", false);
// Polyfill for IE 10 and Firefox <24, where classList.toggle does not
// support the second argument.
if (testElement.classList.contains("c3")) {
var _toggle = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function(token, force) {
if (1 in arguments && !this.contains(token) === !force) {
return force;
} else {
return _toggle.call(this, token);
}
};
}
testElement = null;
}());
}
}
},{}],11:[function(require,module,exports){
/**
* Expose `Emitter`.
*/
if (typeof module !== 'undefined') {
module.exports = Emitter;
}
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks['$' + event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks['$' + event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks['$' + event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],12:[function(require,module,exports){
var DOCUMENT_POSITION_CONTAINED_BY = 16
module.exports = contains
function contains(container, elem) {
if (container.contains) {
return container.contains(elem)
}
var comparison = container.compareDocumentPosition(elem)
return comparison === 0 || comparison & DOCUMENT_POSITION_CONTAINED_BY
}
},{}],13:[function(require,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],14:[function(require,module,exports){
var cof = require('./_cof');
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
},{"./_cof":28}],15:[function(require,module,exports){
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = require('./_wks')('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)require('./_hide')(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
},{"./_hide":50,"./_wks":126}],16:[function(require,module,exports){
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
},{}],17:[function(require,module,exports){
var isObject = require('./_is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./_is-object":59}],18:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = require('./_to-object')
, toIndex = require('./_to-index')
, toLength = require('./_to-length');
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
},{"./_to-index":114,"./_to-length":117,"./_to-object":118}],19:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = require('./_to-object')
, toIndex = require('./_to-index')
, toLength = require('./_to-length');
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
},{"./_to-index":114,"./_to-length":117,"./_to-object":118}],20:[function(require,module,exports){
var forOf = require('./_for-of');
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
},{"./_for-of":47}],21:[function(require,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = require('./_to-iobject')
, toLength = require('./_to-length')
, toIndex = require('./_to-index');
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"./_to-index":114,"./_to-iobject":116,"./_to-length":117}],22:[function(require,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = require('./_ctx')
, IObject = require('./_iobject')
, toObject = require('./_to-object')
, toLength = require('./_to-length')
, asc = require('./_array-species-create');
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"./_array-species-create":25,"./_ctx":35,"./_iobject":55,"./_to-length":117,"./_to-object":118}],23:[function(require,module,exports){
var aFunction = require('./_a-function')
, toObject = require('./_to-object')
, IObject = require('./_iobject')
, toLength = require('./_to-length');
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
},{"./_a-function":13,"./_iobject":55,"./_to-length":117,"./_to-object":118}],24:[function(require,module,exports){
var isObject = require('./_is-object')
, isArray = require('./_is-array')
, SPECIES = require('./_wks')('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
},{"./_is-array":57,"./_is-object":59,"./_wks":126}],25:[function(require,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = require('./_array-species-constructor');
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
},{"./_array-species-constructor":24}],26:[function(require,module,exports){
'use strict';
var aFunction = require('./_a-function')
, isObject = require('./_is-object')
, invoke = require('./_invoke')
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
},{"./_a-function":13,"./_invoke":54,"./_is-object":59}],27:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./_cof')
, TAG = require('./_wks')('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./_cof":28,"./_wks":126}],28:[function(require,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],29:[function(require,module,exports){
'use strict';
var dP = require('./_object-dp').f
, create = require('./_object-create')
, redefineAll = require('./_redefine-all')
, ctx = require('./_ctx')
, anInstance = require('./_an-instance')
, defined = require('./_defined')
, forOf = require('./_for-of')
, $iterDefine = require('./_iter-define')
, step = require('./_iter-step')
, setSpecies = require('./_set-species')
, DESCRIPTORS = require('./_descriptors')
, fastKey = require('./_meta').fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
},{"./_an-instance":16,"./_ctx":35,"./_defined":37,"./_descriptors":38,"./_for-of":47,"./_iter-define":63,"./_iter-step":65,"./_meta":72,"./_object-create":76,"./_object-dp":77,"./_redefine-all":96,"./_set-species":100}],30:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = require('./_classof')
, from = require('./_array-from-iterable');
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
},{"./_array-from-iterable":20,"./_classof":27}],31:[function(require,module,exports){
'use strict';
var redefineAll = require('./_redefine-all')
, getWeak = require('./_meta').getWeak
, anObject = require('./_an-object')
, isObject = require('./_is-object')
, anInstance = require('./_an-instance')
, forOf = require('./_for-of')
, createArrayMethod = require('./_array-methods')
, $has = require('./_has')
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
},{"./_an-instance":16,"./_an-object":17,"./_array-methods":22,"./_for-of":47,"./_has":49,"./_is-object":59,"./_meta":72,"./_redefine-all":96}],32:[function(require,module,exports){
'use strict';
var global = require('./_global')
, $export = require('./_export')
, redefine = require('./_redefine')
, redefineAll = require('./_redefine-all')
, meta = require('./_meta')
, forOf = require('./_for-of')
, anInstance = require('./_an-instance')
, isObject = require('./_is-object')
, fails = require('./_fails')
, $iterDetect = require('./_iter-detect')
, setToStringTag = require('./_set-to-string-tag')
, inheritIfRequired = require('./_inherit-if-required');
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"./_an-instance":16,"./_export":42,"./_fails":44,"./_for-of":47,"./_global":48,"./_inherit-if-required":53,"./_is-object":59,"./_iter-detect":64,"./_meta":72,"./_redefine":97,"./_redefine-all":96,"./_set-to-string-tag":101}],33:[function(require,module,exports){
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],34:[function(require,module,exports){
'use strict';
var $defineProperty = require('./_object-dp')
, createDesc = require('./_property-desc');
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
},{"./_object-dp":77,"./_property-desc":95}],35:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./_a-function');
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);
};
};
},{"./_a-function":13}],36:[function(require,module,exports){
'use strict';
var anObject = require('./_an-object')
, toPrimitive = require('./_to-primitive')
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
},{"./_an-object":17,"./_to-primitive":119}],37:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],38:[function(require,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !require('./_fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_fails":44}],39:[function(require,module,exports){
var isObject = require('./_is-object')
, document = require('./_global').document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"./_global":48,"./_is-object":59}],40:[function(require,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],41:[function(require,module,exports){
// all enumerable object keys, includes symbols
var getKeys = require('./_object-keys')
, gOPS = require('./_object-gops')
, pIE = require('./_object-pie');
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
},{"./_object-gops":83,"./_object-keys":86,"./_object-pie":87}],42:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, hide = require('./_hide')
, redefine = require('./_redefine')
, ctx = require('./_ctx')
, 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
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// 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
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"./_core":33,"./_ctx":35,"./_global":48,"./_hide":50,"./_redefine":97}],43:[function(require,module,exports){
var MATCH = require('./_wks')('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
},{"./_wks":126}],44:[function(require,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],45:[function(require,module,exports){
'use strict';
var hide = require('./_hide')
, redefine = require('./_redefine')
, fails = require('./_fails')
, defined = require('./_defined')
, wks = require('./_wks');
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
},{"./_defined":37,"./_fails":44,"./_hide":50,"./_redefine":97,"./_wks":126}],46:[function(require,module,exports){
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = require('./_an-object');
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
},{"./_an-object":17}],47:[function(require,module,exports){
var ctx = require('./_ctx')
, call = require('./_iter-call')
, isArrayIter = require('./_is-array-iter')
, anObject = require('./_an-object')
, toLength = require('./_to-length')
, getIterFn = require('./core.get-iterator-method')
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
},{"./_an-object":17,"./_ctx":35,"./_is-array-iter":56,"./_iter-call":61,"./_to-length":117,"./core.get-iterator-method":127}],48:[function(require,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
},{}],49:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],50:[function(require,module,exports){
var dP = require('./_object-dp')
, createDesc = require('./_property-desc');
module.exports = require('./_descriptors') ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./_descriptors":38,"./_object-dp":77,"./_property-desc":95}],51:[function(require,module,exports){
module.exports = require('./_global').document && document.documentElement;
},{"./_global":48}],52:[function(require,module,exports){
module.exports = !require('./_descriptors') && !require('./_fails')(function(){
return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_descriptors":38,"./_dom-create":39,"./_fails":44}],53:[function(require,module,exports){
var isObject = require('./_is-object')
, setPrototypeOf = require('./_set-proto').set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
},{"./_is-object":59,"./_set-proto":99}],54:[function(require,module,exports){
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
},{}],55:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./_cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":28}],56:[function(require,module,exports){
// check on default Array iterator
var Iterators = require('./_iterators')
, ITERATOR = require('./_wks')('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"./_iterators":66,"./_wks":126}],57:[function(require,module,exports){
// 7.2.2 IsArray(argument)
var cof = require('./_cof');
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
},{"./_cof":28}],58:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var isObject = require('./_is-object')
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
},{"./_is-object":59}],59:[function(require,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],60:[function(require,module,exports){
// 7.2.8 IsRegExp(argument)
var isObject = require('./_is-object')
, cof = require('./_cof')
, MATCH = require('./_wks')('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
},{"./_cof":28,"./_is-object":59,"./_wks":126}],61:[function(require,module,exports){
// call something on iterator step with safe closing on error
var anObject = require('./_an-object');
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"./_an-object":17}],62:[function(require,module,exports){
'use strict';
var create = require('./_object-create')
, descriptor = require('./_property-desc')
, setToStringTag = require('./_set-to-string-tag')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"./_hide":50,"./_object-create":76,"./_property-desc":95,"./_set-to-string-tag":101,"./_wks":126}],63:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library')
, $export = require('./_export')
, redefine = require('./_redefine')
, hide = require('./_hide')
, has = require('./_has')
, Iterators = require('./_iterators')
, $iterCreate = require('./_iter-create')
, setToStringTag = require('./_set-to-string-tag')
, getPrototypeOf = require('./_object-gpo')
, ITERATOR = require('./_wks')('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"./_export":42,"./_has":49,"./_hide":50,"./_iter-create":62,"./_iterators":66,"./_library":68,"./_object-gpo":84,"./_redefine":97,"./_set-to-string-tag":101,"./_wks":126}],64:[function(require,module,exports){
var ITERATOR = require('./_wks')('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
},{"./_wks":126}],65:[function(require,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],66:[function(require,module,exports){
module.exports = {};
},{}],67:[function(require,module,exports){
var getKeys = require('./_object-keys')
, toIObject = require('./_to-iobject');
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
},{"./_object-keys":86,"./_to-iobject":116}],68:[function(require,module,exports){
module.exports = false;
},{}],69:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
},{}],70:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
},{}],71:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
},{}],72:[function(require,module,exports){
var META = require('./_uid')('meta')
, isObject = require('./_is-object')
, has = require('./_has')
, setDesc = require('./_object-dp').f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !require('./_fails')(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
},{"./_fails":44,"./_has":49,"./_is-object":59,"./_object-dp":77,"./_uid":123}],73:[function(require,module,exports){
var Map = require('./es6.map')
, $export = require('./_export')
, shared = require('./_shared')('metadata')
, store = shared.store || (shared.store = new (require('./es6.weak-map')));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
},{"./_export":42,"./_shared":103,"./es6.map":157,"./es6.weak-map":263}],74:[function(require,module,exports){
var global = require('./_global')
, macrotask = require('./_task').set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = require('./_cof')(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
},{"./_cof":28,"./_global":48,"./_task":113}],75:[function(require,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = require('./_object-keys')
, gOPS = require('./_object-gops')
, pIE = require('./_object-pie')
, toObject = require('./_to-object')
, IObject = require('./_iobject')
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || require('./_fails')(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[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;
} : $assign;
},{"./_fails":44,"./_iobject":55,"./_object-gops":83,"./_object-keys":86,"./_object-pie":87,"./_to-object":118}],76:[function(require,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = require('./_an-object')
, dPs = require('./_object-dps')
, enumBugKeys = require('./_enum-bug-keys')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = require('./_dom-create')('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
require('./_html').appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"./_an-object":17,"./_dom-create":39,"./_enum-bug-keys":40,"./_html":51,"./_object-dps":78,"./_shared-key":102}],77:[function(require,module,exports){
var anObject = require('./_an-object')
, IE8_DOM_DEFINE = require('./_ie8-dom-define')
, toPrimitive = require('./_to-primitive')
, dP = Object.defineProperty;
exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"./_an-object":17,"./_descriptors":38,"./_ie8-dom-define":52,"./_to-primitive":119}],78:[function(require,module,exports){
var dP = require('./_object-dp')
, anObject = require('./_an-object')
, getKeys = require('./_object-keys');
module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"./_an-object":17,"./_descriptors":38,"./_object-dp":77,"./_object-keys":86}],79:[function(require,module,exports){
// Forced replacement prototype accessors methods
module.exports = require('./_library')|| !require('./_fails')(function(){
var K = Math.random();
// In FF throws only define methods
__defineSetter__.call(null, K, function(){ /* empty */});
delete require('./_global')[K];
});
},{"./_fails":44,"./_global":48,"./_library":68}],80:[function(require,module,exports){
var pIE = require('./_object-pie')
, createDesc = require('./_property-desc')
, toIObject = require('./_to-iobject')
, toPrimitive = require('./_to-primitive')
, has = require('./_has')
, IE8_DOM_DEFINE = require('./_ie8-dom-define')
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
},{"./_descriptors":38,"./_has":49,"./_ie8-dom-define":52,"./_object-pie":87,"./_property-desc":95,"./_to-iobject":116,"./_to-primitive":119}],81:[function(require,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = require('./_to-iobject')
, gOPN = require('./_object-gopn').f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
},{"./_object-gopn":82,"./_to-iobject":116}],82:[function(require,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = require('./_object-keys-internal')
, hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
},{"./_enum-bug-keys":40,"./_object-keys-internal":85}],83:[function(require,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],84:[function(require,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = require('./_has')
, toObject = require('./_to-object')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"./_has":49,"./_shared-key":102,"./_to-object":118}],85:[function(require,module,exports){
var has = require('./_has')
, toIObject = require('./_to-iobject')
, arrayIndexOf = require('./_array-includes')(false)
, IE_PROTO = require('./_shared-key')('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"./_array-includes":21,"./_has":49,"./_shared-key":102,"./_to-iobject":116}],86:[function(require,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = require('./_object-keys-internal')
, enumBugKeys = require('./_enum-bug-keys');
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":40,"./_object-keys-internal":85}],87:[function(require,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],88:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
var $export = require('./_export')
, core = require('./_core')
, fails = require('./_fails');
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);
};
},{"./_core":33,"./_export":42,"./_fails":44}],89:[function(require,module,exports){
var getKeys = require('./_object-keys')
, toIObject = require('./_to-iobject')
, isEnum = require('./_object-pie').f;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
},{"./_object-keys":86,"./_object-pie":87,"./_to-iobject":116}],90:[function(require,module,exports){
// all object keys, includes non-enumerable and symbols
var gOPN = require('./_object-gopn')
, gOPS = require('./_object-gops')
, anObject = require('./_an-object')
, Reflect = require('./_global').Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
},{"./_an-object":17,"./_global":48,"./_object-gopn":82,"./_object-gops":83}],91:[function(require,module,exports){
var $parseFloat = require('./_global').parseFloat
, $trim = require('./_string-trim').trim;
module.exports = 1 / $parseFloat(require('./_string-ws') + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
},{"./_global":48,"./_string-trim":111,"./_string-ws":112}],92:[function(require,module,exports){
var $parseInt = require('./_global').parseInt
, $trim = require('./_string-trim').trim
, ws = require('./_string-ws')
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
},{"./_global":48,"./_string-trim":111,"./_string-ws":112}],93:[function(require,module,exports){
'use strict';
var path = require('./_path')
, invoke = require('./_invoke')
, aFunction = require('./_a-function');
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, aLen = arguments.length
, j = 0, k = 0, args;
if(!holder && !aLen)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(aLen > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
},{"./_a-function":13,"./_invoke":54,"./_path":94}],94:[function(require,module,exports){
module.exports = require('./_global');
},{"./_global":48}],95:[function(require,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],96:[function(require,module,exports){
var redefine = require('./_redefine');
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
},{"./_redefine":97}],97:[function(require,module,exports){
var global = require('./_global')
, hide = require('./_hide')
, has = require('./_has')
, SRC = require('./_uid')('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
require('./_core').inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
},{"./_core":33,"./_global":48,"./_has":49,"./_hide":50,"./_uid":123}],98:[function(require,module,exports){
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
},{}],99:[function(require,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = require('./_is-object')
, anObject = require('./_an-object');
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 = require('./_ctx')(Function.call, require('./_object-gopd').f(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
};
},{"./_an-object":17,"./_ctx":35,"./_is-object":59,"./_object-gopd":80}],100:[function(require,module,exports){
'use strict';
var global = require('./_global')
, dP = require('./_object-dp')
, DESCRIPTORS = require('./_descriptors')
, SPECIES = require('./_wks')('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"./_descriptors":38,"./_global":48,"./_object-dp":77,"./_wks":126}],101:[function(require,module,exports){
var def = require('./_object-dp').f
, has = require('./_has')
, TAG = require('./_wks')('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"./_has":49,"./_object-dp":77,"./_wks":126}],102:[function(require,module,exports){
var shared = require('./_shared')('keys')
, uid = require('./_uid');
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":103,"./_uid":123}],103:[function(require,module,exports){
var global = require('./_global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./_global":48}],104:[function(require,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = require('./_an-object')
, aFunction = require('./_a-function')
, SPECIES = require('./_wks')('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"./_a-function":13,"./_an-object":17,"./_wks":126}],105:[function(require,module,exports){
var fails = require('./_fails');
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
},{"./_fails":44}],106:[function(require,module,exports){
var toInteger = require('./_to-integer')
, defined = require('./_defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./_defined":37,"./_to-integer":115}],107:[function(require,module,exports){
// helper for String#{startsWith, endsWith, includes}
var isRegExp = require('./_is-regexp')
, defined = require('./_defined');
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
},{"./_defined":37,"./_is-regexp":60}],108:[function(require,module,exports){
var $export = require('./_export')
, fails = require('./_fails')
, defined = require('./_defined')
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
},{"./_defined":37,"./_export":42,"./_fails":44}],109:[function(require,module,exports){
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = require('./_to-length')
, repeat = require('./_string-repeat')
, defined = require('./_defined');
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength || fillStr == '')return S;
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
},{"./_defined":37,"./_string-repeat":110,"./_to-length":117}],110:[function(require,module,exports){
'use strict';
var toInteger = require('./_to-integer')
, defined = require('./_defined');
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
},{"./_defined":37,"./_to-integer":115}],111:[function(require,module,exports){
var $export = require('./_export')
, defined = require('./_defined')
, fails = require('./_fails')
, spaces = require('./_string-ws')
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
},{"./_defined":37,"./_export":42,"./_fails":44,"./_string-ws":112}],112:[function(require,module,exports){
module.exports = '\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';
},{}],113:[function(require,module,exports){
var ctx = require('./_ctx')
, invoke = require('./_invoke')
, html = require('./_html')
, cel = require('./_dom-create')
, global = require('./_global')
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(require('./_cof')(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
},{"./_cof":28,"./_ctx":35,"./_dom-create":39,"./_global":48,"./_html":51,"./_invoke":54}],114:[function(require,module,exports){
var toInteger = require('./_to-integer')
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":115}],115:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],116:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject')
, defined = require('./_defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./_defined":37,"./_iobject":55}],117:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./_to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":115}],118:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./_defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./_defined":37}],119:[function(require,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = require('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./_is-object":59}],120:[function(require,module,exports){
'use strict';
if(require('./_descriptors')){
var LIBRARY = require('./_library')
, global = require('./_global')
, fails = require('./_fails')
, $export = require('./_export')
, $typed = require('./_typed')
, $buffer = require('./_typed-buffer')
, ctx = require('./_ctx')
, anInstance = require('./_an-instance')
, propertyDesc = require('./_property-desc')
, hide = require('./_hide')
, redefineAll = require('./_redefine-all')
, toInteger = require('./_to-integer')
, toLength = require('./_to-length')
, toIndex = require('./_to-index')
, toPrimitive = require('./_to-primitive')
, has = require('./_has')
, same = require('./_same-value')
, classof = require('./_classof')
, isObject = require('./_is-object')
, toObject = require('./_to-object')
, isArrayIter = require('./_is-array-iter')
, create = require('./_object-create')
, getPrototypeOf = require('./_object-gpo')
, gOPN = require('./_object-gopn').f
, getIterFn = require('./core.get-iterator-method')
, uid = require('./_uid')
, wks = require('./_wks')
, createArrayMethod = require('./_array-methods')
, createArrayIncludes = require('./_array-includes')
, speciesConstructor = require('./_species-constructor')
, ArrayIterators = require('./es6.array.iterator')
, Iterators = require('./_iterators')
, $iterDetect = require('./_iter-detect')
, setSpecies = require('./_set-species')
, arrayFill = require('./_array-fill')
, arrayCopyWithin = require('./_array-copy-within')
, $DP = require('./_object-dp')
, $GOPD = require('./_object-gopd')
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
},{"./_an-instance":16,"./_array-copy-within":18,"./_array-fill":19,"./_array-includes":21,"./_array-methods":22,"./_classof":27,"./_ctx":35,"./_descriptors":38,"./_export":42,"./_fails":44,"./_global":48,"./_has":49,"./_hide":50,"./_is-array-iter":56,"./_is-object":59,"./_iter-detect":64,"./_iterators":66,"./_library":68,"./_object-create":76,"./_object-dp":77,"./_object-gopd":80,"./_object-gopn":82,"./_object-gpo":84,"./_property-desc":95,"./_redefine-all":96,"./_same-value":98,"./_set-species":100,"./_species-constructor":104,"./_to-index":114,"./_to-integer":115,"./_to-length":117,"./_to-object":118,"./_to-primitive":119,"./_typed":122,"./_typed-buffer":121,"./_uid":123,"./_wks":126,"./core.get-iterator-method":127,"./es6.array.iterator":138}],121:[function(require,module,exports){
'use strict';
var global = require('./_global')
, DESCRIPTORS = require('./_descriptors')
, LIBRARY = require('./_library')
, $typed = require('./_typed')
, hide = require('./_hide')
, redefineAll = require('./_redefine-all')
, fails = require('./_fails')
, anInstance = require('./_an-instance')
, toInteger = require('./_to-integer')
, toLength = require('./_to-length')
, gOPN = require('./_object-gopn').f
, dP = require('./_object-dp').f
, arrayFill = require('./_array-fill')
, setToStringTag = require('./_set-to-string-tag')
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if(value * c >= 2){
e++;
c /= 2;
}
if(e + eBias >= eMax){
m = 0;
e = eMax;
} else if(e + eBias >= 1){
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
},{"./_an-instance":16,"./_array-fill":19,"./_descriptors":38,"./_fails":44,"./_global":48,"./_hide":50,"./_library":68,"./_object-dp":77,"./_object-gopn":82,"./_redefine-all":96,"./_set-to-string-tag":101,"./_to-integer":115,"./_to-length":117,"./_typed":122}],122:[function(require,module,exports){
var global = require('./_global')
, hide = require('./_hide')
, uid = require('./_uid')
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
},{"./_global":48,"./_hide":50,"./_uid":123}],123:[function(require,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],124:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, LIBRARY = require('./_library')
, wksExt = require('./_wks-ext')
, defineProperty = require('./_object-dp').f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
},{"./_core":33,"./_global":48,"./_library":68,"./_object-dp":77,"./_wks-ext":125}],125:[function(require,module,exports){
exports.f = require('./_wks');
},{"./_wks":126}],126:[function(require,module,exports){
var store = require('./_shared')('wks')
, uid = require('./_uid')
, Symbol = require('./_global').Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"./_global":48,"./_shared":103,"./_uid":123}],127:[function(require,module,exports){
var classof = require('./_classof')
, ITERATOR = require('./_wks')('iterator')
, Iterators = require('./_iterators');
module.exports = require('./_core').getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./_classof":27,"./_core":33,"./_iterators":66,"./_wks":126}],128:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = require('./_export');
$export($export.P, 'Array', {copyWithin: require('./_array-copy-within')});
require('./_add-to-unscopables')('copyWithin');
},{"./_add-to-unscopables":15,"./_array-copy-within":18,"./_export":42}],129:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $every = require('./_array-methods')(4);
$export($export.P + $export.F * !require('./_strict-method')([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":22,"./_export":42,"./_strict-method":105}],130:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = require('./_export');
$export($export.P, 'Array', {fill: require('./_array-fill')});
require('./_add-to-unscopables')('fill');
},{"./_add-to-unscopables":15,"./_array-fill":19,"./_export":42}],131:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $filter = require('./_array-methods')(2);
$export($export.P + $export.F * !require('./_strict-method')([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":22,"./_export":42,"./_strict-method":105}],132:[function(require,module,exports){
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = require('./_export')
, $find = require('./_array-methods')(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')(KEY);
},{"./_add-to-unscopables":15,"./_array-methods":22,"./_export":42}],133:[function(require,module,exports){
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = require('./_export')
, $find = require('./_array-methods')(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')(KEY);
},{"./_add-to-unscopables":15,"./_array-methods":22,"./_export":42}],134:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $forEach = require('./_array-methods')(0)
, STRICT = require('./_strict-method')([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":22,"./_export":42,"./_strict-method":105}],135:[function(require,module,exports){
'use strict';
var ctx = require('./_ctx')
, $export = require('./_export')
, toObject = require('./_to-object')
, call = require('./_iter-call')
, isArrayIter = require('./_is-array-iter')
, toLength = require('./_to-length')
, createProperty = require('./_create-property')
, getIterFn = require('./core.get-iterator-method');
$export($export.S + $export.F * !require('./_iter-detect')(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
},{"./_create-property":34,"./_ctx":35,"./_export":42,"./_is-array-iter":56,"./_iter-call":61,"./_iter-detect":64,"./_to-length":117,"./_to-object":118,"./core.get-iterator-method":127}],136:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $indexOf = require('./_array-includes')(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
},{"./_array-includes":21,"./_export":42,"./_strict-method":105}],137:[function(require,module,exports){
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = require('./_export');
$export($export.S, 'Array', {isArray: require('./_is-array')});
},{"./_export":42,"./_is-array":57}],138:[function(require,module,exports){
'use strict';
var addToUnscopables = require('./_add-to-unscopables')
, step = require('./_iter-step')
, Iterators = require('./_iterators')
, toIObject = require('./_to-iobject');
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = require('./_iter-define')(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"./_add-to-unscopables":15,"./_iter-define":63,"./_iter-step":65,"./_iterators":66,"./_to-iobject":116}],139:[function(require,module,exports){
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = require('./_export')
, toIObject = require('./_to-iobject')
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (require('./_iobject') != Object || !require('./_strict-method')(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
},{"./_export":42,"./_iobject":55,"./_strict-method":105,"./_to-iobject":116}],140:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toIObject = require('./_to-iobject')
, toInteger = require('./_to-integer')
, toLength = require('./_to-length')
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
},{"./_export":42,"./_strict-method":105,"./_to-integer":115,"./_to-iobject":116,"./_to-length":117}],141:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $map = require('./_array-methods')(1);
$export($export.P + $export.F * !require('./_strict-method')([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":22,"./_export":42,"./_strict-method":105}],142:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, createProperty = require('./_create-property');
// WebKit Array.of isn't generic
$export($export.S + $export.F * require('./_fails')(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
},{"./_create-property":34,"./_export":42,"./_fails":44}],143:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $reduce = require('./_array-reduce');
$export($export.P + $export.F * !require('./_strict-method')([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
},{"./_array-reduce":23,"./_export":42,"./_strict-method":105}],144:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $reduce = require('./_array-reduce');
$export($export.P + $export.F * !require('./_strict-method')([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
},{"./_array-reduce":23,"./_export":42,"./_strict-method":105}],145:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, html = require('./_html')
, cof = require('./_cof')
, toIndex = require('./_to-index')
, toLength = require('./_to-length')
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * require('./_fails')(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
},{"./_cof":28,"./_export":42,"./_fails":44,"./_html":51,"./_to-index":114,"./_to-length":117}],146:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $some = require('./_array-methods')(3);
$export($export.P + $export.F * !require('./_strict-method')([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":22,"./_export":42,"./_strict-method":105}],147:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, aFunction = require('./_a-function')
, toObject = require('./_to-object')
, fails = require('./_fails')
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !require('./_strict-method')($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
},{"./_a-function":13,"./_export":42,"./_fails":44,"./_strict-method":105,"./_to-object":118}],148:[function(require,module,exports){
require('./_set-species')('Array');
},{"./_set-species":100}],149:[function(require,module,exports){
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = require('./_export');
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
},{"./_export":42}],150:[function(require,module,exports){
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = require('./_export')
, fails = require('./_fails')
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
},{"./_export":42,"./_fails":44}],151:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, toPrimitive = require('./_to-primitive');
$export($export.P + $export.F * require('./_fails')(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
},{"./_export":42,"./_fails":44,"./_to-object":118,"./_to-primitive":119}],152:[function(require,module,exports){
var TO_PRIMITIVE = require('./_wks')('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))require('./_hide')(proto, TO_PRIMITIVE, require('./_date-to-primitive'));
},{"./_date-to-primitive":36,"./_hide":50,"./_wks":126}],153:[function(require,module,exports){
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
require('./_redefine')(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
},{"./_redefine":97}],154:[function(require,module,exports){
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = require('./_export');
$export($export.P, 'Function', {bind: require('./_bind')});
},{"./_bind":26,"./_export":42}],155:[function(require,module,exports){
'use strict';
var isObject = require('./_is-object')
, getPrototypeOf = require('./_object-gpo')
, HAS_INSTANCE = require('./_wks')('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))require('./_object-dp').f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
},{"./_is-object":59,"./_object-dp":77,"./_object-gpo":84,"./_wks":126}],156:[function(require,module,exports){
var dP = require('./_object-dp').f
, createDesc = require('./_property-desc')
, has = require('./_has')
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || require('./_descriptors') && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
},{"./_descriptors":38,"./_has":49,"./_object-dp":77,"./_property-desc":95}],157:[function(require,module,exports){
'use strict';
var strong = require('./_collection-strong');
// 23.1 Map Objects
module.exports = require('./_collection')('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
},{"./_collection":32,"./_collection-strong":29}],158:[function(require,module,exports){
// 20.2.2.3 Math.acosh(x)
var $export = require('./_export')
, log1p = require('./_math-log1p')
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
},{"./_export":42,"./_math-log1p":70}],159:[function(require,module,exports){
// 20.2.2.5 Math.asinh(x)
var $export = require('./_export')
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
},{"./_export":42}],160:[function(require,module,exports){
// 20.2.2.7 Math.atanh(x)
var $export = require('./_export')
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
},{"./_export":42}],161:[function(require,module,exports){
// 20.2.2.9 Math.cbrt(x)
var $export = require('./_export')
, sign = require('./_math-sign');
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
},{"./_export":42,"./_math-sign":71}],162:[function(require,module,exports){
// 20.2.2.11 Math.clz32(x)
var $export = require('./_export');
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
},{"./_export":42}],163:[function(require,module,exports){
// 20.2.2.12 Math.cosh(x)
var $export = require('./_export')
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
},{"./_export":42}],164:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
var $export = require('./_export')
, $expm1 = require('./_math-expm1');
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
},{"./_export":42,"./_math-expm1":69}],165:[function(require,module,exports){
// 20.2.2.16 Math.fround(x)
var $export = require('./_export')
, sign = require('./_math-sign')
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
},{"./_export":42,"./_math-sign":71}],166:[function(require,module,exports){
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = require('./_export')
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
},{"./_export":42}],167:[function(require,module,exports){
// 20.2.2.18 Math.imul(x, y)
var $export = require('./_export')
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * require('./_fails')(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
},{"./_export":42,"./_fails":44}],168:[function(require,module,exports){
// 20.2.2.21 Math.log10(x)
var $export = require('./_export');
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
},{"./_export":42}],169:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
var $export = require('./_export');
$export($export.S, 'Math', {log1p: require('./_math-log1p')});
},{"./_export":42,"./_math-log1p":70}],170:[function(require,module,exports){
// 20.2.2.22 Math.log2(x)
var $export = require('./_export');
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
},{"./_export":42}],171:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
var $export = require('./_export');
$export($export.S, 'Math', {sign: require('./_math-sign')});
},{"./_export":42,"./_math-sign":71}],172:[function(require,module,exports){
// 20.2.2.30 Math.sinh(x)
var $export = require('./_export')
, expm1 = require('./_math-expm1')
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * require('./_fails')(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
},{"./_export":42,"./_fails":44,"./_math-expm1":69}],173:[function(require,module,exports){
// 20.2.2.33 Math.tanh(x)
var $export = require('./_export')
, expm1 = require('./_math-expm1')
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
},{"./_export":42,"./_math-expm1":69}],174:[function(require,module,exports){
// 20.2.2.34 Math.trunc(x)
var $export = require('./_export');
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
},{"./_export":42}],175:[function(require,module,exports){
'use strict';
var global = require('./_global')
, has = require('./_has')
, cof = require('./_cof')
, inheritIfRequired = require('./_inherit-if-required')
, toPrimitive = require('./_to-primitive')
, fails = require('./_fails')
, gOPN = require('./_object-gopn').f
, gOPD = require('./_object-gopd').f
, dP = require('./_object-dp').f
, $trim = require('./_string-trim').trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(require('./_object-create')(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = require('./_descriptors') ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
require('./_redefine')(global, NUMBER, $Number);
}
},{"./_cof":28,"./_descriptors":38,"./_fails":44,"./_global":48,"./_has":49,"./_inherit-if-required":53,"./_object-create":76,"./_object-dp":77,"./_object-gopd":80,"./_object-gopn":82,"./_redefine":97,"./_string-trim":111,"./_to-primitive":119}],176:[function(require,module,exports){
// 20.1.2.1 Number.EPSILON
var $export = require('./_export');
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
},{"./_export":42}],177:[function(require,module,exports){
// 20.1.2.2 Number.isFinite(number)
var $export = require('./_export')
, _isFinite = require('./_global').isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
},{"./_export":42,"./_global":48}],178:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var $export = require('./_export');
$export($export.S, 'Number', {isInteger: require('./_is-integer')});
},{"./_export":42,"./_is-integer":58}],179:[function(require,module,exports){
// 20.1.2.4 Number.isNaN(number)
var $export = require('./_export');
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
},{"./_export":42}],180:[function(require,module,exports){
// 20.1.2.5 Number.isSafeInteger(number)
var $export = require('./_export')
, isInteger = require('./_is-integer')
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
},{"./_export":42,"./_is-integer":58}],181:[function(require,module,exports){
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = require('./_export');
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
},{"./_export":42}],182:[function(require,module,exports){
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = require('./_export');
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
},{"./_export":42}],183:[function(require,module,exports){
var $export = require('./_export')
, $parseFloat = require('./_parse-float');
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
},{"./_export":42,"./_parse-float":91}],184:[function(require,module,exports){
var $export = require('./_export')
, $parseInt = require('./_parse-int');
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
},{"./_export":42,"./_parse-int":92}],185:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toInteger = require('./_to-integer')
, aNumberValue = require('./_a-number-value')
, repeat = require('./_string-repeat')
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !require('./_fails')(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
},{"./_a-number-value":14,"./_export":42,"./_fails":44,"./_string-repeat":110,"./_to-integer":115}],186:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $fails = require('./_fails')
, aNumberValue = require('./_a-number-value')
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
},{"./_a-number-value":14,"./_export":42,"./_fails":44}],187:[function(require,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = require('./_export');
$export($export.S + $export.F, 'Object', {assign: require('./_object-assign')});
},{"./_export":42,"./_object-assign":75}],188:[function(require,module,exports){
var $export = require('./_export')
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: require('./_object-create')});
},{"./_export":42,"./_object-create":76}],189:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperties: require('./_object-dps')});
},{"./_descriptors":38,"./_export":42,"./_object-dps":78}],190:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperty: require('./_object-dp').f});
},{"./_descriptors":38,"./_export":42,"./_object-dp":77}],191:[function(require,module,exports){
// 19.1.2.5 Object.freeze(O)
var isObject = require('./_is-object')
, meta = require('./_meta').onFreeze;
require('./_object-sap')('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
},{"./_is-object":59,"./_meta":72,"./_object-sap":88}],192:[function(require,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = require('./_to-iobject')
, $getOwnPropertyDescriptor = require('./_object-gopd').f;
require('./_object-sap')('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"./_object-gopd":80,"./_object-sap":88,"./_to-iobject":116}],193:[function(require,module,exports){
// 19.1.2.7 Object.getOwnPropertyNames(O)
require('./_object-sap')('getOwnPropertyNames', function(){
return require('./_object-gopn-ext').f;
});
},{"./_object-gopn-ext":81,"./_object-sap":88}],194:[function(require,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = require('./_to-object')
, $getPrototypeOf = require('./_object-gpo');
require('./_object-sap')('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
},{"./_object-gpo":84,"./_object-sap":88,"./_to-object":118}],195:[function(require,module,exports){
// 19.1.2.11 Object.isExtensible(O)
var isObject = require('./_is-object');
require('./_object-sap')('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
},{"./_is-object":59,"./_object-sap":88}],196:[function(require,module,exports){
// 19.1.2.12 Object.isFrozen(O)
var isObject = require('./_is-object');
require('./_object-sap')('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
},{"./_is-object":59,"./_object-sap":88}],197:[function(require,module,exports){
// 19.1.2.13 Object.isSealed(O)
var isObject = require('./_is-object');
require('./_object-sap')('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
},{"./_is-object":59,"./_object-sap":88}],198:[function(require,module,exports){
// 19.1.3.10 Object.is(value1, value2)
var $export = require('./_export');
$export($export.S, 'Object', {is: require('./_same-value')});
},{"./_export":42,"./_same-value":98}],199:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./_to-object')
, $keys = require('./_object-keys');
require('./_object-sap')('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./_object-keys":86,"./_object-sap":88,"./_to-object":118}],200:[function(require,module,exports){
// 19.1.2.15 Object.preventExtensions(O)
var isObject = require('./_is-object')
, meta = require('./_meta').onFreeze;
require('./_object-sap')('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
},{"./_is-object":59,"./_meta":72,"./_object-sap":88}],201:[function(require,module,exports){
// 19.1.2.17 Object.seal(O)
var isObject = require('./_is-object')
, meta = require('./_meta').onFreeze;
require('./_object-sap')('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
},{"./_is-object":59,"./_meta":72,"./_object-sap":88}],202:[function(require,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = require('./_export');
$export($export.S, 'Object', {setPrototypeOf: require('./_set-proto').set});
},{"./_export":42,"./_set-proto":99}],203:[function(require,module,exports){
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = require('./_classof')
, test = {};
test[require('./_wks')('toStringTag')] = 'z';
if(test + '' != '[object z]'){
require('./_redefine')(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
},{"./_classof":27,"./_redefine":97,"./_wks":126}],204:[function(require,module,exports){
var $export = require('./_export')
, $parseFloat = require('./_parse-float');
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
},{"./_export":42,"./_parse-float":91}],205:[function(require,module,exports){
var $export = require('./_export')
, $parseInt = require('./_parse-int');
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
},{"./_export":42,"./_parse-int":92}],206:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library')
, global = require('./_global')
, ctx = require('./_ctx')
, classof = require('./_classof')
, $export = require('./_export')
, isObject = require('./_is-object')
, aFunction = require('./_a-function')
, anInstance = require('./_an-instance')
, forOf = require('./_for-of')
, speciesConstructor = require('./_species-constructor')
, task = require('./_task').set
, microtask = require('./_microtask')()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = require('./_redefine-all')($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
require('./_set-to-string-tag')($Promise, PROMISE);
require('./_set-species')(PROMISE);
Wrapper = require('./_core')[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
},{"./_a-function":13,"./_an-instance":16,"./_classof":27,"./_core":33,"./_ctx":35,"./_export":42,"./_for-of":47,"./_global":48,"./_is-object":59,"./_iter-detect":64,"./_library":68,"./_microtask":74,"./_redefine-all":96,"./_set-species":100,"./_set-to-string-tag":101,"./_species-constructor":104,"./_task":113,"./_wks":126}],207:[function(require,module,exports){
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = require('./_export')
, aFunction = require('./_a-function')
, anObject = require('./_an-object')
, rApply = (require('./_global').Reflect || {}).apply
, fApply = Function.apply;
// MS Edge argumentsList argument is optional
$export($export.S + $export.F * !require('./_fails')(function(){
rApply(function(){});
}), 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
var T = aFunction(target)
, L = anObject(argumentsList);
return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L);
}
});
},{"./_a-function":13,"./_an-object":17,"./_export":42,"./_fails":44,"./_global":48}],208:[function(require,module,exports){
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = require('./_export')
, create = require('./_object-create')
, aFunction = require('./_a-function')
, anObject = require('./_an-object')
, isObject = require('./_is-object')
, fails = require('./_fails')
, bind = require('./_bind')
, rConstruct = (require('./_global').Reflect || {}).construct;
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails(function(){
function F(){}
return !(rConstruct(function(){}, [], F) instanceof F);
});
var ARGS_BUG = !fails(function(){
rConstruct(function(){});
});
$export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
switch(args.length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
},{"./_a-function":13,"./_an-object":17,"./_bind":26,"./_export":42,"./_fails":44,"./_global":48,"./_is-object":59,"./_object-create":76}],209:[function(require,module,exports){
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = require('./_object-dp')
, $export = require('./_export')
, anObject = require('./_an-object')
, toPrimitive = require('./_to-primitive');
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * require('./_fails')(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
},{"./_an-object":17,"./_export":42,"./_fails":44,"./_object-dp":77,"./_to-primitive":119}],210:[function(require,module,exports){
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = require('./_export')
, gOPD = require('./_object-gopd').f
, anObject = require('./_an-object');
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
},{"./_an-object":17,"./_export":42,"./_object-gopd":80}],211:[function(require,module,exports){
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = require('./_export')
, anObject = require('./_an-object');
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
require('./_iter-create')(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
},{"./_an-object":17,"./_export":42,"./_iter-create":62}],212:[function(require,module,exports){
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = require('./_object-gopd')
, $export = require('./_export')
, anObject = require('./_an-object');
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
},{"./_an-object":17,"./_export":42,"./_object-gopd":80}],213:[function(require,module,exports){
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = require('./_export')
, getProto = require('./_object-gpo')
, anObject = require('./_an-object');
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
},{"./_an-object":17,"./_export":42,"./_object-gpo":84}],214:[function(require,module,exports){
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = require('./_object-gopd')
, getPrototypeOf = require('./_object-gpo')
, has = require('./_has')
, $export = require('./_export')
, isObject = require('./_is-object')
, anObject = require('./_an-object');
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
},{"./_an-object":17,"./_export":42,"./_has":49,"./_is-object":59,"./_object-gopd":80,"./_object-gpo":84}],215:[function(require,module,exports){
// 26.1.9 Reflect.has(target, propertyKey)
var $export = require('./_export');
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
},{"./_export":42}],216:[function(require,module,exports){
// 26.1.10 Reflect.isExtensible(target)
var $export = require('./_export')
, anObject = require('./_an-object')
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
},{"./_an-object":17,"./_export":42}],217:[function(require,module,exports){
// 26.1.11 Reflect.ownKeys(target)
var $export = require('./_export');
$export($export.S, 'Reflect', {ownKeys: require('./_own-keys')});
},{"./_export":42,"./_own-keys":90}],218:[function(require,module,exports){
// 26.1.12 Reflect.preventExtensions(target)
var $export = require('./_export')
, anObject = require('./_an-object')
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
},{"./_an-object":17,"./_export":42}],219:[function(require,module,exports){
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = require('./_export')
, setProto = require('./_set-proto');
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
},{"./_export":42,"./_set-proto":99}],220:[function(require,module,exports){
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = require('./_object-dp')
, gOPD = require('./_object-gopd')
, getPrototypeOf = require('./_object-gpo')
, has = require('./_has')
, $export = require('./_export')
, createDesc = require('./_property-desc')
, anObject = require('./_an-object')
, isObject = require('./_is-object');
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
},{"./_an-object":17,"./_export":42,"./_has":49,"./_is-object":59,"./_object-dp":77,"./_object-gopd":80,"./_object-gpo":84,"./_property-desc":95}],221:[function(require,module,exports){
var global = require('./_global')
, inheritIfRequired = require('./_inherit-if-required')
, dP = require('./_object-dp').f
, gOPN = require('./_object-gopn').f
, isRegExp = require('./_is-regexp')
, $flags = require('./_flags')
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(require('./_descriptors') && (!CORRECT_NEW || require('./_fails')(function(){
re2[require('./_wks')('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
require('./_redefine')(global, 'RegExp', $RegExp);
}
require('./_set-species')('RegExp');
},{"./_descriptors":38,"./_fails":44,"./_flags":46,"./_global":48,"./_inherit-if-required":53,"./_is-regexp":60,"./_object-dp":77,"./_object-gopn":82,"./_redefine":97,"./_set-species":100,"./_wks":126}],222:[function(require,module,exports){
// 21.2.5.3 get RegExp.prototype.flags()
if(require('./_descriptors') && /./g.flags != 'g')require('./_object-dp').f(RegExp.prototype, 'flags', {
configurable: true,
get: require('./_flags')
});
},{"./_descriptors":38,"./_flags":46,"./_object-dp":77}],223:[function(require,module,exports){
// @@match logic
require('./_fix-re-wks')('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
},{"./_fix-re-wks":45}],224:[function(require,module,exports){
// @@replace logic
require('./_fix-re-wks')('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
},{"./_fix-re-wks":45}],225:[function(require,module,exports){
// @@search logic
require('./_fix-re-wks')('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
},{"./_fix-re-wks":45}],226:[function(require,module,exports){
// @@split logic
require('./_fix-re-wks')('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = require('./_is-regexp')
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
},{"./_fix-re-wks":45,"./_is-regexp":60}],227:[function(require,module,exports){
'use strict';
require('./es6.regexp.flags');
var anObject = require('./_an-object')
, $flags = require('./_flags')
, DESCRIPTORS = require('./_descriptors')
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
require('./_redefine')(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(require('./_fails')(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
},{"./_an-object":17,"./_descriptors":38,"./_fails":44,"./_flags":46,"./_redefine":97,"./es6.regexp.flags":222}],228:[function(require,module,exports){
'use strict';
var strong = require('./_collection-strong');
// 23.2 Set Objects
module.exports = require('./_collection')('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
},{"./_collection":32,"./_collection-strong":29}],229:[function(require,module,exports){
'use strict';
// B.2.3.2 String.prototype.anchor(name)
require('./_string-html')('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
},{"./_string-html":108}],230:[function(require,module,exports){
'use strict';
// B.2.3.3 String.prototype.big()
require('./_string-html')('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
},{"./_string-html":108}],231:[function(require,module,exports){
'use strict';
// B.2.3.4 String.prototype.blink()
require('./_string-html')('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
},{"./_string-html":108}],232:[function(require,module,exports){
'use strict';
// B.2.3.5 String.prototype.bold()
require('./_string-html')('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
},{"./_string-html":108}],233:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $at = require('./_string-at')(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
},{"./_export":42,"./_string-at":106}],234:[function(require,module,exports){
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = require('./_export')
, toLength = require('./_to-length')
, context = require('./_string-context')
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * require('./_fails-is-regexp')(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
},{"./_export":42,"./_fails-is-regexp":43,"./_string-context":107,"./_to-length":117}],235:[function(require,module,exports){
'use strict';
// B.2.3.6 String.prototype.fixed()
require('./_string-html')('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
},{"./_string-html":108}],236:[function(require,module,exports){
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
require('./_string-html')('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
},{"./_string-html":108}],237:[function(require,module,exports){
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
require('./_string-html')('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
},{"./_string-html":108}],238:[function(require,module,exports){
var $export = require('./_export')
, toIndex = require('./_to-index')
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
},{"./_export":42,"./_to-index":114}],239:[function(require,module,exports){
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = require('./_export')
, context = require('./_string-context')
, INCLUDES = 'includes';
$export($export.P + $export.F * require('./_fails-is-regexp')(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"./_export":42,"./_fails-is-regexp":43,"./_string-context":107}],240:[function(require,module,exports){
'use strict';
// B.2.3.9 String.prototype.italics()
require('./_string-html')('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
},{"./_string-html":108}],241:[function(require,module,exports){
'use strict';
var $at = require('./_string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
require('./_iter-define')(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"./_iter-define":63,"./_string-at":106}],242:[function(require,module,exports){
'use strict';
// B.2.3.10 String.prototype.link(url)
require('./_string-html')('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
},{"./_string-html":108}],243:[function(require,module,exports){
var $export = require('./_export')
, toIObject = require('./_to-iobject')
, toLength = require('./_to-length');
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
},{"./_export":42,"./_to-iobject":116,"./_to-length":117}],244:[function(require,module,exports){
var $export = require('./_export');
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: require('./_string-repeat')
});
},{"./_export":42,"./_string-repeat":110}],245:[function(require,module,exports){
'use strict';
// B.2.3.11 String.prototype.small()
require('./_string-html')('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
},{"./_string-html":108}],246:[function(require,module,exports){
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = require('./_export')
, toLength = require('./_to-length')
, context = require('./_string-context')
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * require('./_fails-is-regexp')(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
},{"./_export":42,"./_fails-is-regexp":43,"./_string-context":107,"./_to-length":117}],247:[function(require,module,exports){
'use strict';
// B.2.3.12 String.prototype.strike()
require('./_string-html')('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
},{"./_string-html":108}],248:[function(require,module,exports){
'use strict';
// B.2.3.13 String.prototype.sub()
require('./_string-html')('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
},{"./_string-html":108}],249:[function(require,module,exports){
'use strict';
// B.2.3.14 String.prototype.sup()
require('./_string-html')('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
},{"./_string-html":108}],250:[function(require,module,exports){
'use strict';
// 21.1.3.25 String.prototype.trim()
require('./_string-trim')('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
},{"./_string-trim":111}],251:[function(require,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = require('./_global')
, has = require('./_has')
, DESCRIPTORS = require('./_descriptors')
, $export = require('./_export')
, redefine = require('./_redefine')
, META = require('./_meta').KEY
, $fails = require('./_fails')
, shared = require('./_shared')
, setToStringTag = require('./_set-to-string-tag')
, uid = require('./_uid')
, wks = require('./_wks')
, wksExt = require('./_wks-ext')
, wksDefine = require('./_wks-define')
, keyOf = require('./_keyof')
, enumKeys = require('./_enum-keys')
, isArray = require('./_is-array')
, anObject = require('./_an-object')
, toIObject = require('./_to-iobject')
, toPrimitive = require('./_to-primitive')
, createDesc = require('./_property-desc')
, _create = require('./_object-create')
, gOPNExt = require('./_object-gopn-ext')
, $GOPD = require('./_object-gopd')
, $DP = require('./_object-dp')
, $keys = require('./_object-keys')
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames;
require('./_object-pie').f = $propertyIsEnumerable;
require('./_object-gops').f = $getOwnPropertySymbols;
if(DESCRIPTORS && !require('./_library')){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"./_an-object":17,"./_descriptors":38,"./_enum-keys":41,"./_export":42,"./_fails":44,"./_global":48,"./_has":49,"./_hide":50,"./_is-array":57,"./_keyof":67,"./_library":68,"./_meta":72,"./_object-create":76,"./_object-dp":77,"./_object-gopd":80,"./_object-gopn":82,"./_object-gopn-ext":81,"./_object-gops":83,"./_object-keys":86,"./_object-pie":87,"./_property-desc":95,"./_redefine":97,"./_set-to-string-tag":101,"./_shared":103,"./_to-iobject":116,"./_to-primitive":119,"./_uid":123,"./_wks":126,"./_wks-define":124,"./_wks-ext":125}],252:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $typed = require('./_typed')
, buffer = require('./_typed-buffer')
, anObject = require('./_an-object')
, toIndex = require('./_to-index')
, toLength = require('./_to-length')
, isObject = require('./_is-object')
, ArrayBuffer = require('./_global').ArrayBuffer
, speciesConstructor = require('./_species-constructor')
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * require('./_fails')(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
require('./_set-species')(ARRAY_BUFFER);
},{"./_an-object":17,"./_export":42,"./_fails":44,"./_global":48,"./_is-object":59,"./_set-species":100,"./_species-constructor":104,"./_to-index":114,"./_to-length":117,"./_typed":122,"./_typed-buffer":121}],253:[function(require,module,exports){
var $export = require('./_export');
$export($export.G + $export.W + $export.F * !require('./_typed').ABV, {
DataView: require('./_typed-buffer').DataView
});
},{"./_export":42,"./_typed":122,"./_typed-buffer":121}],254:[function(require,module,exports){
require('./_typed-array')('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],255:[function(require,module,exports){
require('./_typed-array')('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],256:[function(require,module,exports){
require('./_typed-array')('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],257:[function(require,module,exports){
require('./_typed-array')('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],258:[function(require,module,exports){
require('./_typed-array')('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],259:[function(require,module,exports){
require('./_typed-array')('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],260:[function(require,module,exports){
require('./_typed-array')('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],261:[function(require,module,exports){
require('./_typed-array')('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":120}],262:[function(require,module,exports){
require('./_typed-array')('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
},{"./_typed-array":120}],263:[function(require,module,exports){
'use strict';
var each = require('./_array-methods')(0)
, redefine = require('./_redefine')
, meta = require('./_meta')
, assign = require('./_object-assign')
, weak = require('./_collection-weak')
, isObject = require('./_is-object')
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = require('./_collection')('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
},{"./_array-methods":22,"./_collection":32,"./_collection-weak":31,"./_is-object":59,"./_meta":72,"./_object-assign":75,"./_redefine":97}],264:[function(require,module,exports){
'use strict';
var weak = require('./_collection-weak');
// 23.4 WeakSet Objects
require('./_collection')('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
},{"./_collection":32,"./_collection-weak":31}],265:[function(require,module,exports){
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = require('./_export')
, $includes = require('./_array-includes')(true);
$export($export.P, 'Array', {
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')('includes');
},{"./_add-to-unscopables":15,"./_array-includes":21,"./_export":42}],266:[function(require,module,exports){
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = require('./_export')
, microtask = require('./_microtask')()
, process = require('./_global').process
, isNode = require('./_cof')(process) == 'process';
$export($export.G, {
asap: function asap(fn){
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
},{"./_cof":28,"./_export":42,"./_global":48,"./_microtask":74}],267:[function(require,module,exports){
// https://github.com/ljharb/proposal-is-error
var $export = require('./_export')
, cof = require('./_cof');
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
},{"./_cof":28,"./_export":42}],268:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./_export');
$export($export.P + $export.R, 'Map', {toJSON: require('./_collection-to-json')('Map')});
},{"./_collection-to-json":30,"./_export":42}],269:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
},{"./_export":42}],270:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
imulh: function imulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >> 16
, v1 = $v >> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
},{"./_export":42}],271:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
},{"./_export":42}],272:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
umulh: function umulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >>> 16
, v1 = $v >>> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
},{"./_export":42}],273:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, aFunction = require('./_a-function')
, $defineProperty = require('./_object-dp');
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__defineGetter__: function __defineGetter__(P, getter){
$defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
}
});
},{"./_a-function":13,"./_descriptors":38,"./_export":42,"./_object-dp":77,"./_object-forced-pam":79,"./_to-object":118}],274:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, aFunction = require('./_a-function')
, $defineProperty = require('./_object-dp');
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__defineSetter__: function __defineSetter__(P, setter){
$defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
}
});
},{"./_a-function":13,"./_descriptors":38,"./_export":42,"./_object-dp":77,"./_object-forced-pam":79,"./_to-object":118}],275:[function(require,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = require('./_export')
, $entries = require('./_object-to-array')(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
},{"./_export":42,"./_object-to-array":89}],276:[function(require,module,exports){
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = require('./_export')
, ownKeys = require('./_own-keys')
, toIObject = require('./_to-iobject')
, gOPD = require('./_object-gopd')
, createProperty = require('./_create-property');
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, getDesc = gOPD.f
, keys = ownKeys(O)
, result = {}
, i = 0
, key;
while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
return result;
}
});
},{"./_create-property":34,"./_export":42,"./_object-gopd":80,"./_own-keys":90,"./_to-iobject":116}],277:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, toPrimitive = require('./_to-primitive')
, getPrototypeOf = require('./_object-gpo')
, getOwnPropertyDescriptor = require('./_object-gopd').f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__lookupGetter__: function __lookupGetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.get;
} while(O = getPrototypeOf(O));
}
});
},{"./_descriptors":38,"./_export":42,"./_object-forced-pam":79,"./_object-gopd":80,"./_object-gpo":84,"./_to-object":118,"./_to-primitive":119}],278:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, toPrimitive = require('./_to-primitive')
, getPrototypeOf = require('./_object-gpo')
, getOwnPropertyDescriptor = require('./_object-gopd').f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__lookupSetter__: function __lookupSetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.set;
} while(O = getPrototypeOf(O));
}
});
},{"./_descriptors":38,"./_export":42,"./_object-forced-pam":79,"./_object-gopd":80,"./_object-gpo":84,"./_to-object":118,"./_to-primitive":119}],279:[function(require,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = require('./_export')
, $values = require('./_object-to-array')(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
},{"./_export":42,"./_object-to-array":89}],280:[function(require,module,exports){
'use strict';
// https://github.com/zenparsing/es-observable
var $export = require('./_export')
, global = require('./_global')
, core = require('./_core')
, microtask = require('./_microtask')()
, OBSERVABLE = require('./_wks')('observable')
, aFunction = require('./_a-function')
, anObject = require('./_an-object')
, anInstance = require('./_an-instance')
, redefineAll = require('./_redefine-all')
, hide = require('./_hide')
, forOf = require('./_for-of')
, RETURN = forOf.RETURN;
var getMethod = function(fn){
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function(subscription){
var cleanup = subscription._c;
if(cleanup){
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function(subscription){
return subscription._o === undefined;
};
var closeSubscription = function(subscription){
if(!subscriptionClosed(subscription)){
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function(observer, subscriber){
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer)
, subscription = cleanup;
if(cleanup != null){
if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch(e){
observer.error(e);
return;
} if(subscriptionClosed(this))cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe(){ closeSubscription(this); }
});
var SubscriptionObserver = function(subscription){
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if(m)return m.call(observer, value);
} catch(e){
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value){
var subscription = this._s;
if(subscriptionClosed(subscription))throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if(!m)throw value;
value = m.call(observer, value);
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber){
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer){
return new Subscription(observer, this._f);
},
forEach: function forEach(fn){
var that = this;
return new (core.Promise || global.Promise)(function(resolve, reject){
aFunction(fn);
var subscription = that.subscribe({
next : function(value){
try {
return fn(value);
} catch(e){
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x){
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if(method){
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function(observer){
return observable.subscribe(observer);
});
}
return new C(function(observer){
var done = false;
microtask(function(){
if(!done){
try {
if(forOf(x, false, function(it){
observer.next(it);
if(done)return RETURN;
}) === RETURN)return;
} catch(e){
if(done)throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function(){ done = true; };
});
},
of: function of(){
for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function(observer){
var done = false;
microtask(function(){
if(!done){
for(var i = 0; i < items.length; ++i){
observer.next(items[i]);
if(done)return;
} observer.complete();
}
});
return function(){ done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function(){ return this; });
$export($export.G, {Observable: $Observable});
require('./_set-species')('Observable');
},{"./_a-function":13,"./_an-instance":16,"./_an-object":17,"./_core":33,"./_export":42,"./_for-of":47,"./_global":48,"./_hide":50,"./_microtask":74,"./_redefine-all":96,"./_set-species":100,"./_wks":126}],281:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
},{"./_an-object":17,"./_metadata":73}],282:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
},{"./_an-object":17,"./_metadata":73}],283:[function(require,module,exports){
var Set = require('./es6.set')
, from = require('./_array-from-iterable')
, metadata = require('./_metadata')
, anObject = require('./_an-object')
, getPrototypeOf = require('./_object-gpo')
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"./_an-object":17,"./_array-from-iterable":20,"./_metadata":73,"./_object-gpo":84,"./es6.set":228}],284:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, getPrototypeOf = require('./_object-gpo')
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":17,"./_metadata":73,"./_object-gpo":84}],285:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"./_an-object":17,"./_metadata":73}],286:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":17,"./_metadata":73}],287:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, getPrototypeOf = require('./_object-gpo')
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":17,"./_metadata":73,"./_object-gpo":84}],288:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":17,"./_metadata":73}],289:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, aFunction = require('./_a-function')
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
},{"./_a-function":13,"./_an-object":17,"./_metadata":73}],290:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./_export');
$export($export.P + $export.R, 'Set', {toJSON: require('./_collection-to-json')('Set')});
},{"./_collection-to-json":30,"./_export":42}],291:[function(require,module,exports){
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = require('./_export')
, $at = require('./_string-at')(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
},{"./_export":42,"./_string-at":106}],292:[function(require,module,exports){
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = require('./_export')
, defined = require('./_defined')
, toLength = require('./_to-length')
, isRegExp = require('./_is-regexp')
, getFlags = require('./_flags')
, RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function(regexp, string){
this._r = regexp;
this._s = string;
};
require('./_iter-create')($RegExpStringIterator, 'RegExp String', function next(){
var match = this._r.exec(this._s);
return {value: match, done: match === null};
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp){
defined(this);
if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
var S = String(this)
, flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
, rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
},{"./_defined":37,"./_export":42,"./_flags":46,"./_is-regexp":60,"./_iter-create":62,"./_to-length":117}],293:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = require('./_export')
, $pad = require('./_string-pad');
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
},{"./_export":42,"./_string-pad":109}],294:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = require('./_export')
, $pad = require('./_string-pad');
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
},{"./_export":42,"./_string-pad":109}],295:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./_string-trim')('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
},{"./_string-trim":111}],296:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./_string-trim')('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
},{"./_string-trim":111}],297:[function(require,module,exports){
require('./_wks-define')('asyncIterator');
},{"./_wks-define":124}],298:[function(require,module,exports){
require('./_wks-define')('observable');
},{"./_wks-define":124}],299:[function(require,module,exports){
// https://github.com/ljharb/proposal-global
var $export = require('./_export');
$export($export.S, 'System', {global: require('./_global')});
},{"./_export":42,"./_global":48}],300:[function(require,module,exports){
var $iterators = require('./es6.array.iterator')
, redefine = require('./_redefine')
, global = require('./_global')
, hide = require('./_hide')
, Iterators = require('./_iterators')
, wks = require('./_wks')
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
}
}
},{"./_global":48,"./_hide":50,"./_iterators":66,"./_redefine":97,"./_wks":126,"./es6.array.iterator":138}],301:[function(require,module,exports){
var $export = require('./_export')
, $task = require('./_task');
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
},{"./_export":42,"./_task":113}],302:[function(require,module,exports){
// ie9- setTimeout & setInterval additional parameters fix
var global = require('./_global')
, $export = require('./_export')
, invoke = require('./_invoke')
, partial = require('./_partial')
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
},{"./_export":42,"./_global":48,"./_invoke":54,"./_partial":93}],303:[function(require,module,exports){
require('./modules/es6.symbol');
require('./modules/es6.object.create');
require('./modules/es6.object.define-property');
require('./modules/es6.object.define-properties');
require('./modules/es6.object.get-own-property-descriptor');
require('./modules/es6.object.get-prototype-of');
require('./modules/es6.object.keys');
require('./modules/es6.object.get-own-property-names');
require('./modules/es6.object.freeze');
require('./modules/es6.object.seal');
require('./modules/es6.object.prevent-extensions');
require('./modules/es6.object.is-frozen');
require('./modules/es6.object.is-sealed');
require('./modules/es6.object.is-extensible');
require('./modules/es6.object.assign');
require('./modules/es6.object.is');
require('./modules/es6.object.set-prototype-of');
require('./modules/es6.object.to-string');
require('./modules/es6.function.bind');
require('./modules/es6.function.name');
require('./modules/es6.function.has-instance');
require('./modules/es6.parse-int');
require('./modules/es6.parse-float');
require('./modules/es6.number.constructor');
require('./modules/es6.number.to-fixed');
require('./modules/es6.number.to-precision');
require('./modules/es6.number.epsilon');
require('./modules/es6.number.is-finite');
require('./modules/es6.number.is-integer');
require('./modules/es6.number.is-nan');
require('./modules/es6.number.is-safe-integer');
require('./modules/es6.number.max-safe-integer');
require('./modules/es6.number.min-safe-integer');
require('./modules/es6.number.parse-float');
require('./modules/es6.number.parse-int');
require('./modules/es6.math.acosh');
require('./modules/es6.math.asinh');
require('./modules/es6.math.atanh');
require('./modules/es6.math.cbrt');
require('./modules/es6.math.clz32');
require('./modules/es6.math.cosh');
require('./modules/es6.math.expm1');
require('./modules/es6.math.fround');
require('./modules/es6.math.hypot');
require('./modules/es6.math.imul');
require('./modules/es6.math.log10');
require('./modules/es6.math.log1p');
require('./modules/es6.math.log2');
require('./modules/es6.math.sign');
require('./modules/es6.math.sinh');
require('./modules/es6.math.tanh');
require('./modules/es6.math.trunc');
require('./modules/es6.string.from-code-point');
require('./modules/es6.string.raw');
require('./modules/es6.string.trim');
require('./modules/es6.string.iterator');
require('./modules/es6.string.code-point-at');
require('./modules/es6.string.ends-with');
require('./modules/es6.string.includes');
require('./modules/es6.string.repeat');
require('./modules/es6.string.starts-with');
require('./modules/es6.string.anchor');
require('./modules/es6.string.big');
require('./modules/es6.string.blink');
require('./modules/es6.string.bold');
require('./modules/es6.string.fixed');
require('./modules/es6.string.fontcolor');
require('./modules/es6.string.fontsize');
require('./modules/es6.string.italics');
require('./modules/es6.string.link');
require('./modules/es6.string.small');
require('./modules/es6.string.strike');
require('./modules/es6.string.sub');
require('./modules/es6.string.sup');
require('./modules/es6.date.now');
require('./modules/es6.date.to-json');
require('./modules/es6.date.to-iso-string');
require('./modules/es6.date.to-string');
require('./modules/es6.date.to-primitive');
require('./modules/es6.array.is-array');
require('./modules/es6.array.from');
require('./modules/es6.array.of');
require('./modules/es6.array.join');
require('./modules/es6.array.slice');
require('./modules/es6.array.sort');
require('./modules/es6.array.for-each');
require('./modules/es6.array.map');
require('./modules/es6.array.filter');
require('./modules/es6.array.some');
require('./modules/es6.array.every');
require('./modules/es6.array.reduce');
require('./modules/es6.array.reduce-right');
require('./modules/es6.array.index-of');
require('./modules/es6.array.last-index-of');
require('./modules/es6.array.copy-within');
require('./modules/es6.array.fill');
require('./modules/es6.array.find');
require('./modules/es6.array.find-index');
require('./modules/es6.array.species');
require('./modules/es6.array.iterator');
require('./modules/es6.regexp.constructor');
require('./modules/es6.regexp.to-string');
require('./modules/es6.regexp.flags');
require('./modules/es6.regexp.match');
require('./modules/es6.regexp.replace');
require('./modules/es6.regexp.search');
require('./modules/es6.regexp.split');
require('./modules/es6.promise');
require('./modules/es6.map');
require('./modules/es6.set');
require('./modules/es6.weak-map');
require('./modules/es6.weak-set');
require('./modules/es6.typed.array-buffer');
require('./modules/es6.typed.data-view');
require('./modules/es6.typed.int8-array');
require('./modules/es6.typed.uint8-array');
require('./modules/es6.typed.uint8-clamped-array');
require('./modules/es6.typed.int16-array');
require('./modules/es6.typed.uint16-array');
require('./modules/es6.typed.int32-array');
require('./modules/es6.typed.uint32-array');
require('./modules/es6.typed.float32-array');
require('./modules/es6.typed.float64-array');
require('./modules/es6.reflect.apply');
require('./modules/es6.reflect.construct');
require('./modules/es6.reflect.define-property');
require('./modules/es6.reflect.delete-property');
require('./modules/es6.reflect.enumerate');
require('./modules/es6.reflect.get');
require('./modules/es6.reflect.get-own-property-descriptor');
require('./modules/es6.reflect.get-prototype-of');
require('./modules/es6.reflect.has');
require('./modules/es6.reflect.is-extensible');
require('./modules/es6.reflect.own-keys');
require('./modules/es6.reflect.prevent-extensions');
require('./modules/es6.reflect.set');
require('./modules/es6.reflect.set-prototype-of');
require('./modules/es7.array.includes');
require('./modules/es7.string.at');
require('./modules/es7.string.pad-start');
require('./modules/es7.string.pad-end');
require('./modules/es7.string.trim-left');
require('./modules/es7.string.trim-right');
require('./modules/es7.string.match-all');
require('./modules/es7.symbol.async-iterator');
require('./modules/es7.symbol.observable');
require('./modules/es7.object.get-own-property-descriptors');
require('./modules/es7.object.values');
require('./modules/es7.object.entries');
require('./modules/es7.object.define-getter');
require('./modules/es7.object.define-setter');
require('./modules/es7.object.lookup-getter');
require('./modules/es7.object.lookup-setter');
require('./modules/es7.map.to-json');
require('./modules/es7.set.to-json');
require('./modules/es7.system.global');
require('./modules/es7.error.is-error');
require('./modules/es7.math.iaddh');
require('./modules/es7.math.isubh');
require('./modules/es7.math.imulh');
require('./modules/es7.math.umulh');
require('./modules/es7.reflect.define-metadata');
require('./modules/es7.reflect.delete-metadata');
require('./modules/es7.reflect.get-metadata');
require('./modules/es7.reflect.get-metadata-keys');
require('./modules/es7.reflect.get-own-metadata');
require('./modules/es7.reflect.get-own-metadata-keys');
require('./modules/es7.reflect.has-metadata');
require('./modules/es7.reflect.has-own-metadata');
require('./modules/es7.reflect.metadata');
require('./modules/es7.asap');
require('./modules/es7.observable');
require('./modules/web.timers');
require('./modules/web.immediate');
require('./modules/web.dom.iterable');
module.exports = require('./modules/_core');
},{"./modules/_core":33,"./modules/es6.array.copy-within":128,"./modules/es6.array.every":129,"./modules/es6.array.fill":130,"./modules/es6.array.filter":131,"./modules/es6.array.find":133,"./modules/es6.array.find-index":132,"./modules/es6.array.for-each":134,"./modules/es6.array.from":135,"./modules/es6.array.index-of":136,"./modules/es6.array.is-array":137,"./modules/es6.array.iterator":138,"./modules/es6.array.join":139,"./modules/es6.array.last-index-of":140,"./modules/es6.array.map":141,"./modules/es6.array.of":142,"./modules/es6.array.reduce":144,"./modules/es6.array.reduce-right":143,"./modules/es6.array.slice":145,"./modules/es6.array.some":146,"./modules/es6.array.sort":147,"./modules/es6.array.species":148,"./modules/es6.date.now":149,"./modules/es6.date.to-iso-string":150,"./modules/es6.date.to-json":151,"./modules/es6.date.to-primitive":152,"./modules/es6.date.to-string":153,"./modules/es6.function.bind":154,"./modules/es6.function.has-instance":155,"./modules/es6.function.name":156,"./modules/es6.map":157,"./modules/es6.math.acosh":158,"./modules/es6.math.asinh":159,"./modules/es6.math.atanh":160,"./modules/es6.math.cbrt":161,"./modules/es6.math.clz32":162,"./modules/es6.math.cosh":163,"./modules/es6.math.expm1":164,"./modules/es6.math.fround":165,"./modules/es6.math.hypot":166,"./modules/es6.math.imul":167,"./modules/es6.math.log10":168,"./modules/es6.math.log1p":169,"./modules/es6.math.log2":170,"./modules/es6.math.sign":171,"./modules/es6.math.sinh":172,"./modules/es6.math.tanh":173,"./modules/es6.math.trunc":174,"./modules/es6.number.constructor":175,"./modules/es6.number.epsilon":176,"./modules/es6.number.is-finite":177,"./modules/es6.number.is-integer":178,"./modules/es6.number.is-nan":179,"./modules/es6.number.is-safe-integer":180,"./modules/es6.number.max-safe-integer":181,"./modules/es6.number.min-safe-integer":182,"./modules/es6.number.parse-float":183,"./modules/es6.number.parse-int":184,"./modules/es6.number.to-fixed":185,"./modules/es6.number.to-precision":186,"./modules/es6.object.assign":187,"./modules/es6.object.create":188,"./modules/es6.object.define-properties":189,"./modules/es6.object.define-property":190,"./modules/es6.object.freeze":191,"./modules/es6.object.get-own-property-descriptor":192,"./modules/es6.object.get-own-property-names":193,"./modules/es6.object.get-prototype-of":194,"./modules/es6.object.is":198,"./modules/es6.object.is-extensible":195,"./modules/es6.object.is-frozen":196,"./modules/es6.object.is-sealed":197,"./modules/es6.object.keys":199,"./modules/es6.object.prevent-extensions":200,"./modules/es6.object.seal":201,"./modules/es6.object.set-prototype-of":202,"./modules/es6.object.to-string":203,"./modules/es6.parse-float":204,"./modules/es6.parse-int":205,"./modules/es6.promise":206,"./modules/es6.reflect.apply":207,"./modules/es6.reflect.construct":208,"./modules/es6.reflect.define-property":209,"./modules/es6.reflect.delete-property":210,"./modules/es6.reflect.enumerate":211,"./modules/es6.reflect.get":214,"./modules/es6.reflect.get-own-property-descriptor":212,"./modules/es6.reflect.get-prototype-of":213,"./modules/es6.reflect.has":215,"./modules/es6.reflect.is-extensible":216,"./modules/es6.reflect.own-keys":217,"./modules/es6.reflect.prevent-extensions":218,"./modules/es6.reflect.set":220,"./modules/es6.reflect.set-prototype-of":219,"./modules/es6.regexp.constructor":221,"./modules/es6.regexp.flags":222,"./modules/es6.regexp.match":223,"./modules/es6.regexp.replace":224,"./modules/es6.regexp.search":225,"./modules/es6.regexp.split":226,"./modules/es6.regexp.to-string":227,"./modules/es6.set":228,"./modules/es6.string.anchor":229,"./modules/es6.string.big":230,"./modules/es6.string.blink":231,"./modules/es6.string.bold":232,"./modules/es6.string.code-point-at":233,"./modules/es6.string.ends-with":234,"./modules/es6.string.fixed":235,"./modules/es6.string.fontcolor":236,"./modules/es6.string.fontsize":237,"./modules/es6.string.from-code-point":238,"./modules/es6.string.includes":239,"./modules/es6.string.italics":240,"./modules/es6.string.iterator":241,"./modules/es6.string.link":242,"./modules/es6.string.raw":243,"./modules/es6.string.repeat":244,"./modules/es6.string.small":245,"./modules/es6.string.starts-with":246,"./modules/es6.string.strike":247,"./modules/es6.string.sub":248,"./modules/es6.string.sup":249,"./modules/es6.string.trim":250,"./modules/es6.symbol":251,"./modules/es6.typed.array-buffer":252,"./modules/es6.typed.data-view":253,"./modules/es6.typed.float32-array":254,"./modules/es6.typed.float64-array":255,"./modules/es6.typed.int16-array":256,"./modules/es6.typed.int32-array":257,"./modules/es6.typed.int8-array":258,"./modules/es6.typed.uint16-array":259,"./modules/es6.typed.uint32-array":260,"./modules/es6.typed.uint8-array":261,"./modules/es6.typed.uint8-clamped-array":262,"./modules/es6.weak-map":263,"./modules/es6.weak-set":264,"./modules/es7.array.includes":265,"./modules/es7.asap":266,"./modules/es7.error.is-error":267,"./modules/es7.map.to-json":268,"./modules/es7.math.iaddh":269,"./modules/es7.math.imulh":270,"./modules/es7.math.isubh":271,"./modules/es7.math.umulh":272,"./modules/es7.object.define-getter":273,"./modules/es7.object.define-setter":274,"./modules/es7.object.entries":275,"./modules/es7.object.get-own-property-descriptors":276,"./modules/es7.object.lookup-getter":277,"./modules/es7.object.lookup-setter":278,"./modules/es7.object.values":279,"./modules/es7.observable":280,"./modules/es7.reflect.define-metadata":281,"./modules/es7.reflect.delete-metadata":282,"./modules/es7.reflect.get-metadata":284,"./modules/es7.reflect.get-metadata-keys":283,"./modules/es7.reflect.get-own-metadata":286,"./modules/es7.reflect.get-own-metadata-keys":285,"./modules/es7.reflect.has-metadata":287,"./modules/es7.reflect.has-own-metadata":288,"./modules/es7.reflect.metadata":289,"./modules/es7.set.to-json":290,"./modules/es7.string.at":291,"./modules/es7.string.match-all":292,"./modules/es7.string.pad-end":293,"./modules/es7.string.pad-start":294,"./modules/es7.string.trim-left":295,"./modules/es7.string.trim-right":296,"./modules/es7.symbol.async-iterator":297,"./modules/es7.symbol.observable":298,"./modules/es7.system.global":299,"./modules/web.dom.iterable":300,"./modules/web.immediate":301,"./modules/web.timers":302}],304:[function(require,module,exports){
(function (Buffer){
// 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":329}],305:[function(require,module,exports){
// create-error.js 0.3.1
// (c) 2013 Tim Griesser
// This source may be freely distributed under the MIT license.
(function(factory) {
"use strict";
// A simple utility for subclassing the "Error"
// object in multiple environments, while maintaining
// relevant stack traces, messages, and prototypes.
factory(function() {
var toString = Object.prototype.toString;
// Creates an new error type with a "name",
// and any additional properties that should be set
// on the error instance.
return function() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
var name = getName(args);
var target = getTarget(args);
var properties = getProps(args);
function ErrorCtor(message, obj) {
attachProps(this, properties);
attachProps(this, obj);
this.message = (message || this.message);
if (message instanceof Error) {
this.message = message.message;
this.stack = message.stack;
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
function Err() { this.constructor = ErrorCtor; }
Err.prototype = target['prototype'];
ErrorCtor.prototype = new Err();
ErrorCtor.prototype.name = ('' + name) || 'CustomError';
return ErrorCtor;
};
// Just a few helpers to clean up the function above
// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
function getName(args) {
if (args.length === 0) return '';
return isError(args[0]) ? (args[1] || '') : args[0];
}
function getTarget(args) {
if (args.length === 0) return Error;
return isError(args[0]) ? args[0] : Error;
}
function getProps(args) {
if (args.length === 0) return null;
return isError(args[0]) ? args[2] : args[1];
}
function inheritedKeys(obj) {
var ret = [];
for (var key in obj) {
ret.push(key);
}
return ret;
}
// Right now we're just assuming that a function in the first argument is an error.
function isError(obj) {
return (typeof obj === "function");
}
// We don't need the full underscore check here, since it should either be
// an object-literal, or nothing at all.
function isObject(obj) {
return (obj && typeof obj === "object" && toString.call(obj) === "[object Object]");
}
// Used to attach attributes to the error object in the constructor.
function attachProps(context, target) {
if (isObject(target)) {
var keys = inheritedKeys(target);
for (var i = 0, l = keys.length; i < l; ++i) {
context[keys[i]] = clone(target[keys[i]]);
}
}
}
// Don't need the full-out "clone" mechanism here, since if you're
// trying to set things other than empty arrays/objects on your
// sub-classed `Error` object, you're probably doing it wrong.
function clone(target) {
if (target == null || typeof target !== "object") return target;
var cloned = target.constructor ? target.constructor() : Object.create(null);
for (var attr in target) {
if (target.hasOwnProperty(attr)) {
cloned[attr] = target[attr];
}
}
return cloned;
}
});
// Boilerplate UMD definition block...
})(function(createErrorLib) {
if (typeof define === "function" && define.amd) {
define(createErrorLib);
} else if (typeof exports === 'object') {
module.exports = createErrorLib();
} else {
var root = this;
var lastcreateError = root.createError;
var createError = root.createError = createErrorLib();
createError.noConflict = function() {
root.createError = lastcreateError;
return createError;
};
}
});
},{}],306:[function(require,module,exports){
module.exports = function () {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] !== undefined) return arguments[i];
}
};
},{}],307:[function(require,module,exports){
var util = require('util'),
events = require('events'),
EventEmitter = events.EventEmitter
module.exports = function() {
var Despot = function() {
if (arguments.callee._singletonInstance) {
return arguments.callee._singletonInstance
}
arguments.callee._singletonInstance = this
EventEmitter.call(this)
}
util.inherits(Despot, EventEmitter)
return new Despot()
}()
},{"events":314,"util":368}],308:[function(require,module,exports){
'use strict'
var document = require('global/document')
var Event = require('geval')
var Keys = require('./keys')
module.exports = Visibility
function Visibility () {
var keys = Keys(document)
if (!keys) return noopShim()
return {
visible: visible,
onChange: Event(listen)
}
function visible () {
return !document[keys.hidden]
}
function listen (broadcast) {
document.addEventListener(keys.event, function onVisibilityChange () {
broadcast(visible())
})
}
}
function noopShim () {
return {
visible: function () {
return true
},
onChange: noop
}
}
function noop () {}
},{"./keys":309,"geval":318,"global/document":319}],309:[function(require,module,exports){
'use strict'
module.exports = keys
function keys (document) {
var prefix = detectPrefix(document)
if (prefix == null) return
return {
hidden: lowercaseFirst(prefix + 'Hidden'),
event: prefix + 'visibilitychange'
}
}
function detectPrefix (document) {
if (document.hidden != null) return ''
if (document.mozHidden != null) return 'moz'
if (document.msHidden != null) return 'ms'
if (document.webkitHidden != null) return 'webkit'
}
function lowercaseFirst (string) {
return string.substring(0, 1).toLowerCase() + string.substring(1)
}
},{}],310:[function(require,module,exports){
(function (process,Buffer){
var stream = require('readable-stream')
var eos = require('end-of-stream')
var inherits = require('inherits')
var shift = require('stream-shift')
var SIGNAL_FLUSH = new Buffer([0])
var onuncork = function(self, fn) {
if (self._corked) self.once('uncork', fn)
else fn()
}
var destroyer = function(self, end) {
return function(err) {
if (err) self.destroy(err.message === 'premature close' ? null : err)
else if (end && !self._ended) self.end()
}
}
var end = function(ws, fn) {
if (!ws) return fn()
if (ws._writableState && ws._writableState.finished) return fn()
if (ws._writableState) return ws.end(fn)
ws.end()
fn()
}
var toStreams2 = function(rs) {
return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
}
var Duplexify = function(writable, readable, opts) {
if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
stream.Duplex.call(this, opts)
this._writable = null
this._readable = null
this._readable2 = null
this._forwardDestroy = !opts || opts.destroy !== false
this._forwardEnd = !opts || opts.end !== false
this._corked = 1 // start corked
this._ondrain = null
this._drained = false
this._forwarding = false
this._unwrite = null
this._unread = null
this._ended = false
this.destroyed = false
if (writable) this.setWritable(writable)
if (readable) this.setReadable(readable)
}
inherits(Duplexify, stream.Duplex)
Duplexify.obj = function(writable, readable, opts) {
if (!opts) opts = {}
opts.objectMode = true
opts.highWaterMark = 16
return new Duplexify(writable, readable, opts)
}
Duplexify.prototype.cork = function() {
if (++this._corked === 1) this.emit('cork')
}
Duplexify.prototype.uncork = function() {
if (this._corked && --this._corked === 0) this.emit('uncork')
}
Duplexify.prototype.setWritable = function(writable) {
if (this._unwrite) this._unwrite()
if (this.destroyed) {
if (writable && writable.destroy) writable.destroy()
return
}
if (writable === null || writable === false) {
this.end()
return
}
var self = this
var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
var ondrain = function() {
var ondrain = self._ondrain
self._ondrain = null
if (ondrain) ondrain()
}
var clear = function() {
self._writable.removeListener('drain', ondrain)
unend()
}
if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
this._writable = writable
this._writable.on('drain', ondrain)
this._unwrite = clear
this.uncork() // always uncork setWritable
}
Duplexify.prototype.setReadable = function(readable) {
if (this._unread) this._unread()
if (this.destroyed) {
if (readable && readable.destroy) readable.destroy()
return
}
if (readable === null || readable === false) {
this.push(null)
this.resume()
return
}
var self = this
var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
var onreadable = function() {
self._forward()
}
var onend = function() {
self.push(null)
}
var clear = function() {
self._readable2.removeListener('readable', onreadable)
self._readable2.removeListener('end', onend)
unend()
}
this._drained = true
this._readable = readable
this._readable2 = readable._readableState ? readable : toStreams2(readable)
this._readable2.on('readable', onreadable)
this._readable2.on('end', onend)
this._unread = clear
this._forward()
}
Duplexify.prototype._read = function() {
this._drained = true
this._forward()
}
Duplexify.prototype._forward = function() {
if (this._forwarding || !this._readable2 || !this._drained) return
this._forwarding = true
var data
while (this._drained && (data = shift(this._readable2)) !== null) {
if (this.destroyed) continue
this._drained = this.push(data)
}
this._forwarding = false
}
Duplexify.prototype.destroy = function(err) {
if (this.destroyed) return
this.destroyed = true
var self = this
process.nextTick(function() {
self._destroy(err)
})
}
Duplexify.prototype._destroy = function(err) {
if (err) {
var ondrain = this._ondrain
this._ondrain = null
if (ondrain) ondrain(err)
else this.emit('error', err)
}
if (this._forwardDestroy) {
if (this._readable && this._readable.destroy) this._readable.destroy()
if (this._writable && this._writable.destroy) this._writable.destroy()
}
this.emit('close')
}
Duplexify.prototype._write = function(data, enc, cb) {
if (this.destroyed) return cb()
if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
if (data === SIGNAL_FLUSH) return this._finish(cb)
if (!this._writable) return cb()
if (this._writable.write(data) === false) this._ondrain = cb
else cb()
}
Duplexify.prototype._finish = function(cb) {
var self = this
this.emit('preend')
onuncork(this, function() {
end(self._forwardEnd && self._writable, function() {
// haxx to not emit prefinish twice
if (self._writableState.prefinished === false) self._writableState.prefinished = true
self.emit('prefinish')
onuncork(self, cb)
})
})
}
Duplexify.prototype.end = function(data, enc, cb) {
if (typeof data === 'function') return this.end(null, null, data)
if (typeof enc === 'function') return this.end(data, null, enc)
this._ended = true
if (data) this.write(data)
if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
return stream.Writable.prototype.end.call(this, cb)
}
module.exports = Duplexify
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":339,"buffer":7,"end-of-stream":311,"inherits":325,"readable-stream":350,"stream-shift":355}],311:[function(require,module,exports){
var once = require('once');
var noop = function() {};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === 'function';
};
var eos = function(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || (opts.readable !== false && stream.readable);
var writable = opts.writable || (opts.writable !== false && stream.writable);
var onlegacyfinish = function() {
if (!stream.writable) onfinish();
};
var onfinish = function() {
writable = false;
if (!readable) callback();
};
var onend = function() {
readable = false;
if (!writable) callback();
};
var onclose = function() {
if (readable && !(rs && rs.ended)) return callback(new Error('premature close'));
if (writable && !(ws && ws.ended)) return callback(new Error('premature close'));
};
var onrequest = function() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();
else stream.on('request', onrequest);
} else if (writable && !ws) { // legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', callback);
stream.on('close', onclose);
return function() {
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('end', onend);
stream.removeListener('error', callback);
stream.removeListener('close', onclose);
};
};
module.exports = eos;
},{"once":312}],312:[function(require,module,exports){
var wrappy = require('wrappy')
module.exports = wrappy(once)
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
})
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
},{"wrappy":372}],313:[function(require,module,exports){
// element-closest | CC0-1.0 | github.com/jonathantneal/closest
(function (ElementProto) {
if (typeof ElementProto.matches !== 'function') {
ElementProto.matches = ElementProto.msMatchesSelector || ElementProto.mozMatchesSelector || ElementProto.webkitMatchesSelector || function matches(selector) {
var element = this;
var elements = (element.document || element.ownerDocument).querySelectorAll(selector);
var index = 0;
while (elements[index] && elements[index] !== element) {
++index;
}
return Boolean(elements[index]);
};
}
if (typeof ElementProto.closest !== 'function') {
ElementProto.closest = function closest(selector) {
var element = this;
while (element && element.nodeType === 1) {
if (element.matches(selector)) {
return element;
}
element = element.parentNode;
}
return null;
};
}
})(window.Element.prototype);
},{}],314:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} 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;
}
},{}],315:[function(require,module,exports){
(function (global){
"use strict";
/**
* filesize
*
* @copyright 2017 Jason Mulligan <jason.mulligan@avoidwork.com>
* @license BSD-3-Clause
* @version 3.5.9
*/
(function (global) {
var b = /^(b|B)$/,
symbol = {
iec: {
bits: ["b", "Kib", "Mib", "Gib", "Tib", "Pib", "Eib", "Zib", "Yib"],
bytes: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
},
jedec: {
bits: ["b", "Kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Yb"],
bytes: ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
}
},
fullform = {
iec: ["", "kibi", "mebi", "gibi", "tebi", "pebi", "exbi", "zebi", "yobi"],
jedec: ["", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta"]
};
/**
* filesize
*
* @method filesize
* @param {Mixed} arg String, Int or Float to transform
* @param {Object} descriptor [Optional] Flags
* @return {String} Readable file size String
*/
function filesize(arg) {
var descriptor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var result = [],
val = 0,
e = void 0,
base = void 0,
bits = void 0,
ceil = void 0,
full = void 0,
fullforms = void 0,
neg = void 0,
num = void 0,
output = void 0,
round = void 0,
unix = void 0,
spacer = void 0,
standard = void 0,
symbols = void 0;
if (isNaN(arg)) {
throw new Error("Invalid arguments");
}
bits = descriptor.bits === true;
unix = descriptor.unix === true;
base = descriptor.base || 2;
round = descriptor.round !== undefined ? descriptor.round : unix ? 1 : 2;
spacer = descriptor.spacer !== undefined ? descriptor.spacer : unix ? "" : " ";
symbols = descriptor.symbols || descriptor.suffixes || {};
standard = base === 2 ? descriptor.standard || "jedec" : "jedec";
output = descriptor.output || "string";
full = descriptor.fullform === true;
fullforms = descriptor.fullforms instanceof Array ? descriptor.fullforms : [];
e = descriptor.exponent !== undefined ? descriptor.exponent : -1;
num = Number(arg);
neg = num < 0;
ceil = base > 2 ? 1000 : 1024;
// Flipping a negative number to determine the size
if (neg) {
num = -num;
}
// Determining the exponent
if (e === -1 || isNaN(e)) {
e = Math.floor(Math.log(num) / Math.log(ceil));
if (e < 0) {
e = 0;
}
}
// Exceeding supported length, time to reduce & multiply
if (e > 8) {
e = 8;
}
// Zero is now a special case because bytes divide by 1
if (num === 0) {
result[0] = 0;
result[1] = unix ? "" : symbol[standard][bits ? "bits" : "bytes"][e];
} else {
val = num / (base === 2 ? Math.pow(2, e * 10) : Math.pow(1000, e));
if (bits) {
val = val * 8;
if (val >= ceil && e < 8) {
val = val / ceil;
e++;
}
}
result[0] = Number(val.toFixed(e > 0 ? round : 0));
result[1] = base === 10 && e === 1 ? bits ? "kb" : "kB" : symbol[standard][bits ? "bits" : "bytes"][e];
if (unix) {
result[1] = standard === "jedec" ? result[1].charAt(0) : e > 0 ? result[1].replace(/B$/, "") : result[1];
if (b.test(result[1])) {
result[0] = Math.floor(result[0]);
result[1] = "";
}
}
}
// Decorating a 'diff'
if (neg) {
result[0] = -result[0];
}
// Applying custom symbol
result[1] = symbols[result[1]] || result[1];
// Returning Array, Object, or String (default)
if (output === "array") {
return result;
}
if (output === "exponent") {
return e;
}
if (output === "object") {
return { value: result[0], suffix: result[1], symbol: result[1] };
}
if (full) {
result[1] = fullforms[e] ? fullforms[e] : fullform[standard][e] + (bits ? "bit" : "byte") + (result[0] === 1 ? "" : "s");
}
return result.join(spacer);
}
// Partial application for functional programming
filesize.partial = function (opt) {
return function (arg) {
return filesize(arg, opt);
};
};
// CommonJS, AMD, script tag
if (typeof exports !== "undefined") {
module.exports = filesize;
} else if (typeof define === "function" && define.amd) {
define(function () {
return filesize;
});
} else {
global.filesize = filesize;
}
})(typeof window !== "undefined" ? window : global);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],316:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var NODE_LIST_CLASSES = {
'[object HTMLCollection]': true,
'[object NodeList]': true,
'[object RadioNodeList]': true
};
// .type values for elements which can appear in .elements and should be ignored
var IGNORED_ELEMENT_TYPES = {
'button': true,
'fieldset': true,
// 'keygen': true,
// 'output': true,
'reset': true,
'submit': true
};
var CHECKED_INPUT_TYPES = {
'checkbox': true,
'radio': true
};
var TRIM_RE = /^\s+|\s+$/g;
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
/**
* @param {HTMLFormElement} form
* @param {Object} options
* @return {Object.<string,(string|Array.<string>)>} an object containing
* submittable value(s) held in the form's .elements collection, with
* properties named as per element names or ids.
*/
function getFormData(form) {
var options = arguments.length <= 1 || arguments[1] === undefined ? { trim: false } : arguments[1];
if (!form) {
throw new Error('A form is required by getFormData, was given form=' + form);
}
var data = {};
var elementName = undefined;
var elementNames = [];
var elementNameLookup = {};
// Get unique submittable element names for the form
for (var i = 0, l = form.elements.length; i < l; i++) {
var element = form.elements[i];
if (IGNORED_ELEMENT_TYPES[element.type] || element.disabled) {
continue;
}
elementName = element.name || element.id;
if (elementName && !elementNameLookup[elementName]) {
elementNames.push(elementName);
elementNameLookup[elementName] = true;
}
}
// Extract element data name-by-name for consistent handling of special cases
// around elements which contain multiple inputs.
for (var i = 0, l = elementNames.length; i < l; i++) {
elementName = elementNames[i];
var value = getNamedFormElementData(form, elementName, options);
if (value != null) {
data[elementName] = value;
}
}
return data;
}
/**
* @param {HTMLFormElement} form
* @param {string} elementName
* @param {Object} options
* @return {(string|Array.<string>)} submittable value(s) in the form for a
* named element from its .elements collection, or null if there was no
* element with that name or the element had no submittable value(s).
*/
function getNamedFormElementData(form, elementName) {
var options = arguments.length <= 2 || arguments[2] === undefined ? { trim: false } : arguments[2];
if (!form) {
throw new Error('A form is required by getNamedFormElementData, was given form=' + form);
}
if (!elementName && toString.call(elementName) !== '[object String]') {
throw new Error('A form element name is required by getNamedFormElementData, was given elementName=' + elementName);
}
var element = form.elements[elementName];
if (!element || element.disabled) {
return null;
}
if (!NODE_LIST_CLASSES[toString.call(element)]) {
return getFormElementValue(element, options.trim);
}
// Deal with multiple form controls which have the same name
var data = [];
var allRadios = true;
for (var i = 0, l = element.length; i < l; i++) {
if (element[i].disabled) {
continue;
}
if (allRadios && element[i].type !== 'radio') {
allRadios = false;
}
var value = getFormElementValue(element[i], options.trim);
if (value != null) {
data = data.concat(value);
}
}
// Special case for an element with multiple same-named inputs which were all
// radio buttons: if there was a selected value, only return the value.
if (allRadios && data.length === 1) {
return data[0];
}
return data.length > 0 ? data : null;
}
/**
* @param {HTMLElement} element a form element.
* @param {booleam} trim should values for text entry inputs be trimmed?
* @return {(string|Array.<string>|File|Array.<File>)} the element's submittable
* value(s), or null if it had none.
*/
function getFormElementValue(element, trim) {
var value = null;
var type = element.type;
if (type === 'select-one') {
if (element.options.length) {
value = element.options[element.selectedIndex].value;
}
return value;
}
if (type === 'select-multiple') {
value = [];
for (var i = 0, l = element.options.length; i < l; i++) {
if (element.options[i].selected) {
value.push(element.options[i].value);
}
}
if (value.length === 0) {
value = null;
}
return value;
}
// If a file input doesn't have a files attribute, fall through to using its
// value attribute.
if (type === 'file' && 'files' in element) {
if (element.multiple) {
value = slice.call(element.files);
if (value.length === 0) {
value = null;
}
} else {
// Should be null if not present, according to the spec
value = element.files[0];
}
return value;
}
if (!CHECKED_INPUT_TYPES[type]) {
value = trim ? element.value.replace(TRIM_RE, '') : element.value;
} else if (element.checked) {
value = element.value;
}
return value;
}
getFormData.getNamedFormElementData = getNamedFormElementData;
exports['default'] = getFormData;
module.exports = exports['default'];
},{}],317:[function(require,module,exports){
module.exports = Event
function Event() {
var listeners = []
return { broadcast: broadcast, listen: event }
function broadcast(value) {
for (var i = 0; i < listeners.length; i++) {
listeners[i](value)
}
}
function event(listener) {
listeners.push(listener)
return removeListener
function removeListener() {
var index = listeners.indexOf(listener)
if (index !== -1) {
listeners.splice(index, 1)
}
}
}
}
},{}],318:[function(require,module,exports){
var Event = require('./event.js')
module.exports = Source
function Source(broadcaster) {
var tuple = Event()
broadcaster(tuple.broadcast)
return tuple.listen
}
},{"./event.js":317}],319:[function(require,module,exports){
(function (global){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = require('min-document');
var doccy;
if (typeof document !== 'undefined') {
doccy = document;
} else {
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":4}],320:[function(require,module,exports){
module.exports = shim
function shim (element, value) {
if (value === undefined) {
return element.style.display === 'none'
}
element.style.display = value ? 'none' : ''
}
},{}],321:[function(require,module,exports){
// HumanizeDuration.js - http://git.io/j0HgmQ
;(function () {
var languages = {
ar: {
y: function (c) { return c === 1 ? 'سنة' : 'سنوات' },
mo: function (c) { return c === 1 ? 'شهر' : 'أشهر' },
w: function (c) { return c === 1 ? 'أسبوع' : 'أسابيع' },
d: function (c) { return c === 1 ? 'يوم' : 'أيام' },
h: function (c) { return c === 1 ? 'ساعة' : 'ساعات' },
m: function (c) { return c === 1 ? 'دقيقة' : 'دقائق' },
s: function (c) { return c === 1 ? 'ثانية' : 'ثواني' },
ms: function (c) { return c === 1 ? 'جزء من الثانية' : 'أجزاء من الثانية' },
decimal: ','
},
ca: {
y: function (c) { return 'any' + (c !== 1 ? 's' : '') },
mo: function (c) { return 'mes' + (c !== 1 ? 'os' : '') },
w: function (c) { return 'setman' + (c !== 1 ? 'es' : 'a') },
d: function (c) { return 'di' + (c !== 1 ? 'es' : 'a') },
h: function (c) { return 'hor' + (c !== 1 ? 'es' : 'a') },
m: function (c) { return 'minut' + (c !== 1 ? 's' : '') },
s: function (c) { return 'segon' + (c !== 1 ? 's' : '') },
ms: function (c) { return 'milisegon' + (c !== 1 ? 's' : '') },
decimal: ','
},
cs: {
y: function (c) { return ['rok', 'roku', 'roky', 'let'][getCzechForm(c)] },
mo: function (c) { return ['měsíc', 'měsíce', 'měsíce', 'měsíců'][getCzechForm(c)] },
w: function (c) { return ['týden', 'týdne', 'týdny', 'týdnů'][getCzechForm(c)] },
d: function (c) { return ['den', 'dne', 'dny', 'dní'][getCzechForm(c)] },
h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodin'][getCzechForm(c)] },
m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getCzechForm(c)] },
s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getCzechForm(c)] },
ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getCzechForm(c)] },
decimal: ','
},
da: {
y: 'år',
mo: function (c) { return 'måned' + (c !== 1 ? 'er' : '') },
w: function (c) { return 'uge' + (c !== 1 ? 'r' : '') },
d: function (c) { return 'dag' + (c !== 1 ? 'e' : '') },
h: function (c) { return 'time' + (c !== 1 ? 'r' : '') },
m: function (c) { return 'minut' + (c !== 1 ? 'ter' : '') },
s: function (c) { return 'sekund' + (c !== 1 ? 'er' : '') },
ms: function (c) { return 'millisekund' + (c !== 1 ? 'er' : '') },
decimal: ','
},
de: {
y: function (c) { return 'Jahr' + (c !== 1 ? 'e' : '') },
mo: function (c) { return 'Monat' + (c !== 1 ? 'e' : '') },
w: function (c) { return 'Woche' + (c !== 1 ? 'n' : '') },
d: function (c) { return 'Tag' + (c !== 1 ? 'e' : '') },
h: function (c) { return 'Stunde' + (c !== 1 ? 'n' : '') },
m: function (c) { return 'Minute' + (c !== 1 ? 'n' : '') },
s: function (c) { return 'Sekunde' + (c !== 1 ? 'n' : '') },
ms: function (c) { return 'Millisekunde' + (c !== 1 ? 'n' : '') },
decimal: ','
},
en: {
y: function (c) { return 'year' + (c !== 1 ? 's' : '') },
mo: function (c) { return 'month' + (c !== 1 ? 's' : '') },
w: function (c) { return 'week' + (c !== 1 ? 's' : '') },
d: function (c) { return 'day' + (c !== 1 ? 's' : '') },
h: function (c) { return 'hour' + (c !== 1 ? 's' : '') },
m: function (c) { return 'minute' + (c !== 1 ? 's' : '') },
s: function (c) { return 'second' + (c !== 1 ? 's' : '') },
ms: function (c) { return 'millisecond' + (c !== 1 ? 's' : '') },
decimal: '.'
},
es: {
y: function (c) { return 'año' + (c !== 1 ? 's' : '') },
mo: function (c) { return 'mes' + (c !== 1 ? 'es' : '') },
w: function (c) { return 'semana' + (c !== 1 ? 's' : '') },
d: function (c) { return 'día' + (c !== 1 ? 's' : '') },
h: function (c) { return 'hora' + (c !== 1 ? 's' : '') },
m: function (c) { return 'minuto' + (c !== 1 ? 's' : '') },
s: function (c) { return 'segundo' + (c !== 1 ? 's' : '') },
ms: function (c) { return 'milisegundo' + (c !== 1 ? 's' : '') },
decimal: ','
},
fi: {
y: function (c) { return c === 1 ? 'vuosi' : 'vuotta' },
mo: function (c) { return c === 1 ? 'kuukausi' : 'kuukautta' },
w: function (c) { return 'viikko' + (c !== 1 ? 'a' : '') },
d: function (c) { return 'päivä' + (c !== 1 ? 'ä' : '') },
h: function (c) { return 'tunti' + (c !== 1 ? 'a' : '') },
m: function (c) { return 'minuutti' + (c !== 1 ? 'a' : '') },
s: function (c) { return 'sekunti' + (c !== 1 ? 'a' : '') },
ms: function (c) { return 'millisekunti' + (c !== 1 ? 'a' : '') },
decimal: ','
},
fr: {
y: function (c) { return 'an' + (c !== 1 ? 's' : '') },
mo: 'mois',
w: function (c) { return 'semaine' + (c !== 1 ? 's' : '') },
d: function (c) { return 'jour' + (c !== 1 ? 's' : '') },
h: function (c) { return 'heure' + (c !== 1 ? 's' : '') },
m: function (c) { return 'minute' + (c !== 1 ? 's' : '') },
s: function (c) { return 'seconde' + (c !== 1 ? 's' : '') },
ms: function (c) { return 'milliseconde' + (c !== 1 ? 's' : '') },
decimal: ','
},
gr: {
y: function (c) { return c === 1 ? 'χρόνος' : 'χρόνια' },
mo: function (c) { return c === 1 ? 'μήνας' : 'μήνες' },
w: function (c) { return c === 1 ? 'εβδομάδα' : 'εβδομάδες' },
d: function (c) { return c === 1 ? 'μέρα' : 'μέρες' },
h: function (c) { return c === 1 ? 'ώρα' : 'ώρες' },
m: function (c) { return c === 1 ? 'λεπτό' : 'λεπτά' },
s: function (c) { return c === 1 ? 'δευτερόλεπτο' : 'δευτερόλεπτα' },
ms: function (c) { return c === 1 ? 'χιλιοστό του δευτερολέπτου' : 'χιλιοστά του δευτερολέπτου' },
decimal: ','
},
hu: {
y: 'év',
mo: 'hónap',
w: 'hét',
d: 'nap',
h: 'óra',
m: 'perc',
s: 'másodperc',
ms: 'ezredmásodperc',
decimal: ','
},
id: {
y: 'tahun',
mo: 'bulan',
w: 'minggu',
d: 'hari',
h: 'jam',
m: 'menit',
s: 'detik',
ms: 'milidetik',
decimal: '.'
},
is: {
y: 'ár',
mo: function (c) { return 'mánuð' + (c !== 1 ? 'ir' : 'ur') },
w: function (c) { return 'vik' + (c !== 1 ? 'ur' : 'a') },
d: function (c) { return 'dag' + (c !== 1 ? 'ar' : 'ur') },
h: function (c) { return 'klukkutím' + (c !== 1 ? 'ar' : 'i') },
m: function (c) { return 'mínút' + (c !== 1 ? 'ur' : 'a') },
s: function (c) { return 'sekúnd' + (c !== 1 ? 'ur' : 'a') },
ms: function (c) { return 'millisekúnd' + (c !== 1 ? 'ur' : 'a') },
decimal: '.'
},
it: {
y: function (c) { return 'ann' + (c !== 1 ? 'i' : 'o') },
mo: function (c) { return 'mes' + (c !== 1 ? 'i' : 'e') },
w: function (c) { return 'settiman' + (c !== 1 ? 'e' : 'a') },
d: function (c) { return 'giorn' + (c !== 1 ? 'i' : 'o') },
h: function (c) { return 'or' + (c !== 1 ? 'e' : 'a') },
m: function (c) { return 'minut' + (c !== 1 ? 'i' : 'o') },
s: function (c) { return 'second' + (c !== 1 ? 'i' : 'o') },
ms: function (c) { return 'millisecond' + (c !== 1 ? 'i' : 'o') },
decimal: ','
},
ja: {
y: '年',
mo: '月',
w: '週',
d: '日',
h: '時間',
m: '分',
s: '秒',
ms: 'ミリ秒',
decimal: '.'
},
ko: {
y: '년',
mo: '개월',
w: '주일',
d: '일',
h: '시간',
m: '분',
s: '초',
ms: '밀리 초',
decimal: '.'
},
lt: {
y: function (c) { return ((c % 10 === 0) || (c % 100 >= 10 && c % 100 <= 20)) ? 'metų' : 'metai' },
mo: function (c) { return ['mėnuo', 'mėnesiai', 'mėnesių'][getLithuanianForm(c)] },
w: function (c) { return ['savaitė', 'savaitės', 'savaičių'][getLithuanianForm(c)] },
d: function (c) { return ['diena', 'dienos', 'dienų'][getLithuanianForm(c)] },
h: function (c) { return ['valanda', 'valandos', 'valandų'][getLithuanianForm(c)] },
m: function (c) { return ['minutė', 'minutės', 'minučių'][getLithuanianForm(c)] },
s: function (c) { return ['sekundė', 'sekundės', 'sekundžių'][getLithuanianForm(c)] },
ms: function (c) { return ['milisekundė', 'milisekundės', 'milisekundžių'][getLithuanianForm(c)] },
decimal: ','
},
ms: {
y: 'tahun',
mo: 'bulan',
w: 'minggu',
d: 'hari',
h: 'jam',
m: 'minit',
s: 'saat',
ms: 'milisaat',
decimal: '.'
},
nl: {
y: 'jaar',
mo: function (c) { return c === 1 ? 'maand' : 'maanden' },
w: function (c) { return c === 1 ? 'week' : 'weken' },
d: function (c) { return c === 1 ? 'dag' : 'dagen' },
h: 'uur',
m: function (c) { return c === 1 ? 'minuut' : 'minuten' },
s: function (c) { return c === 1 ? 'seconde' : 'seconden' },
ms: function (c) { return c === 1 ? 'milliseconde' : 'milliseconden' },
decimal: ','
},
no: {
y: 'år',
mo: function (c) { return 'måned' + (c !== 1 ? 'er' : '') },
w: function (c) { return 'uke' + (c !== 1 ? 'r' : '') },
d: function (c) { return 'dag' + (c !== 1 ? 'er' : '') },
h: function (c) { return 'time' + (c !== 1 ? 'r' : '') },
m: function (c) { return 'minutt' + (c !== 1 ? 'er' : '') },
s: function (c) { return 'sekund' + (c !== 1 ? 'er' : '') },
ms: function (c) { return 'millisekund' + (c !== 1 ? 'er' : '') },
decimal: ','
},
pl: {
y: function (c) { return ['rok', 'roku', 'lata', 'lat'][getPolishForm(c)] },
mo: function (c) { return ['miesiąc', 'miesiąca', 'miesiące', 'miesięcy'][getPolishForm(c)] },
w: function (c) { return ['tydzień', 'tygodnia', 'tygodnie', 'tygodni'][getPolishForm(c)] },
d: function (c) { return ['dzień', 'dnia', 'dni', 'dni'][getPolishForm(c)] },
h: function (c) { return ['godzina', 'godziny', 'godziny', 'godzin'][getPolishForm(c)] },
m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getPolishForm(c)] },
s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getPolishForm(c)] },
ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getPolishForm(c)] },
decimal: ','
},
pt: {
y: function (c) { return 'ano' + (c !== 1 ? 's' : '') },
mo: function (c) { return c !== 1 ? 'meses' : 'mês' },
w: function (c) { return 'semana' + (c !== 1 ? 's' : '') },
d: function (c) { return 'dia' + (c !== 1 ? 's' : '') },
h: function (c) { return 'hora' + (c !== 1 ? 's' : '') },
m: function (c) { return 'minuto' + (c !== 1 ? 's' : '') },
s: function (c) { return 'segundo' + (c !== 1 ? 's' : '') },
ms: function (c) { return 'milissegundo' + (c !== 1 ? 's' : '') },
decimal: ','
},
ru: {
y: function (c) { return ['лет', 'год', 'года'][getSlavicForm(c)] },
mo: function (c) { return ['месяцев', 'месяц', 'месяца'][getSlavicForm(c)] },
w: function (c) { return ['недель', 'неделя', 'недели'][getSlavicForm(c)] },
d: function (c) { return ['дней', 'день', 'дня'][getSlavicForm(c)] },
h: function (c) { return ['часов', 'час', 'часа'][getSlavicForm(c)] },
m: function (c) { return ['минут', 'минута', 'минуты'][getSlavicForm(c)] },
s: function (c) { return ['секунд', 'секунда', 'секунды'][getSlavicForm(c)] },
ms: function (c) { return ['миллисекунд', 'миллисекунда', 'миллисекунды'][getSlavicForm(c)] },
decimal: ','
},
uk: {
y: function (c) { return ['років', 'рік', 'роки'][getSlavicForm(c)] },
mo: function (c) { return ['місяців', 'місяць', 'місяці'][getSlavicForm(c)] },
w: function (c) { return ['неділь', 'неділя', 'неділі'][getSlavicForm(c)] },
d: function (c) { return ['днів', 'день', 'дні'][getSlavicForm(c)] },
h: function (c) { return ['годин', 'година', 'години'][getSlavicForm(c)] },
m: function (c) { return ['хвилин', 'хвилина', 'хвилини'][getSlavicForm(c)] },
s: function (c) { return ['секунд', 'секунда', 'секунди'][getSlavicForm(c)] },
ms: function (c) { return ['мілісекунд', 'мілісекунда', 'мілісекунди'][getSlavicForm(c)] },
decimal: ','
},
sv: {
y: 'år',
mo: function (c) { return 'månad' + (c !== 1 ? 'er' : '') },
w: function (c) { return 'veck' + (c !== 1 ? 'or' : 'a') },
d: function (c) { return 'dag' + (c !== 1 ? 'ar' : '') },
h: function (c) { return 'timm' + (c !== 1 ? 'ar' : 'e') },
m: function (c) { return 'minut' + (c !== 1 ? 'er' : '') },
s: function (c) { return 'sekund' + (c !== 1 ? 'er' : '') },
ms: function (c) { return 'millisekund' + (c !== 1 ? 'er' : '') },
decimal: ','
},
tr: {
y: 'yıl',
mo: 'ay',
w: 'hafta',
d: 'gün',
h: 'saat',
m: 'dakika',
s: 'saniye',
ms: 'milisaniye',
decimal: ','
},
vi: {
y: 'năm',
mo: 'tháng',
w: 'tuần',
d: 'ngày',
h: 'giờ',
m: 'phút',
s: 'giây',
ms: 'mili giây',
decimal: ','
},
zh_CN: {
y: '年',
mo: '个月',
w: '周',
d: '天',
h: '小时',
m: '分钟',
s: '秒',
ms: '毫秒',
decimal: '.'
},
zh_TW: {
y: '年',
mo: '個月',
w: '周',
d: '天',
h: '小時',
m: '分鐘',
s: '秒',
ms: '毫秒',
decimal: '.'
}
}
// You can create a humanizer, which returns a function with default
// parameters.
function humanizer (passedOptions) {
var result = function humanizer (ms, humanizerOptions) {
var options = extend({}, result, humanizerOptions || {})
return doHumanization(ms, options)
}
return extend(result, {
language: 'en',
delimiter: ', ',
spacer: ' ',
conjunction: '',
serialComma: true,
units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'],
languages: {},
round: false,
unitMeasures: {
y: 31557600000,
mo: 2629800000,
w: 604800000,
d: 86400000,
h: 3600000,
m: 60000,
s: 1000,
ms: 1
}
}, passedOptions)
}
// The main function is just a wrapper around a default humanizer.
var humanizeDuration = humanizer({})
// doHumanization does the bulk of the work.
function doHumanization (ms, options) {
var i, len, piece
// Make sure we have a positive number.
// Has the nice sideffect of turning Number objects into primitives.
ms = Math.abs(ms)
var dictionary = options.languages[options.language] || languages[options.language]
if (!dictionary) {
throw new Error('No language ' + dictionary + '.')
}
var pieces = []
// Start at the top and keep removing units, bit by bit.
var unitName, unitMS, unitCount
for (i = 0, len = options.units.length; i < len; i++) {
unitName = options.units[i]
unitMS = options.unitMeasures[unitName]
// What's the number of full units we can fit?
if (i + 1 === len) {
unitCount = ms / unitMS
} else {
unitCount = Math.floor(ms / unitMS)
}
// Add the string.
pieces.push({
unitCount: unitCount,
unitName: unitName
})
// Remove what we just figured out.
ms -= unitCount * unitMS
}
var firstOccupiedUnitIndex = 0
for (i = 0; i < pieces.length; i++) {
if (pieces[i].unitCount) {
firstOccupiedUnitIndex = i
break
}
}
if (options.round) {
var ratioToLargerUnit, previousPiece
for (i = pieces.length - 1; i >= 0; i--) {
piece = pieces[i]
piece.unitCount = Math.round(piece.unitCount)
if (i === 0) { break }
previousPiece = pieces[i - 1]
ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName]
if ((piece.unitCount % ratioToLargerUnit) === 0 || (options.largest && ((options.largest - 1) < (i - firstOccupiedUnitIndex)))) {
previousPiece.unitCount += piece.unitCount / ratioToLargerUnit
piece.unitCount = 0
}
}
}
var result = []
for (i = 0, pieces.length; i < len; i++) {
piece = pieces[i]
if (piece.unitCount) {
result.push(render(piece.unitCount, piece.unitName, dictionary, options))
}
if (result.length === options.largest) { break }
}
if (result.length) {
if (!options.conjunction || result.length === 1) {
return result.join(options.delimiter)
} else if (result.length === 2) {
return result.join(options.conjunction)
} else if (result.length > 2) {
return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1)
}
} else {
return render(0, options.units[options.units.length - 1], dictionary, options)
}
}
function render (count, type, dictionary, options) {
var decimal
if (options.decimal === void 0) {
decimal = dictionary.decimal
} else {
decimal = options.decimal
}
var countStr = count.toString().replace('.', decimal)
var dictionaryValue = dictionary[type]
var word
if (typeof dictionaryValue === 'function') {
word = dictionaryValue(count)
} else {
word = dictionaryValue
}
return countStr + options.spacer + word
}
function extend (destination) {
var source
for (var i = 1; i < arguments.length; i++) {
source = arguments[i]
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
destination[prop] = source[prop]
}
}
}
return destination
}
// Internal helper function for Czech language.
function getCzechForm (c) {
if (c === 1) {
return 0
} else if (Math.floor(c) !== c) {
return 1
} else if (c % 10 >= 2 && c % 10 <= 4 && c % 100 < 10) {
return 2
} else {
return 3
}
}
// Internal helper function for Polish language.
function getPolishForm (c) {
if (c === 1) {
return 0
} else if (Math.floor(c) !== c) {
return 1
} else if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) {
return 2
} else {
return 3
}
}
// Internal helper function for Russian and Ukranian languages.
function getSlavicForm (c) {
if (Math.floor(c) !== c) {
return 2
} else if ((c % 100 >= 5 && c % 100 <= 20) || (c % 10 >= 5 && c % 10 <= 9) || c % 10 === 0) {
return 0
} else if (c % 10 === 1) {
return 1
} else if (c > 1) {
return 2
} else {
return 0
}
}
// Internal helper function for Lithuanian language.
function getLithuanianForm (c) {
if (c === 1 || (c % 10 === 1 && c % 100 > 20)) {
return 0
} else if (Math.floor(c) !== c || (c % 10 >= 2 && c % 100 > 20) || (c % 10 >= 2 && c % 100 < 10)) {
return 1
} else {
return 2
}
}
humanizeDuration.getSupportedLanguages = function getSupportedLanguages () {
var result = []
for (var language in languages) {
if (languages.hasOwnProperty(language)) {
result.push(language)
}
}
return result
}
humanizeDuration.humanizer = humanizer
if (typeof define === 'function' && define.amd) {
define(function () {
return humanizeDuration
})
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = humanizeDuration
} else {
this.humanizeDuration = humanizeDuration
}
})(); // eslint-disable-line semi
},{}],322:[function(require,module,exports){
var split = require('browser-split')
var ClassList = require('class-list')
var w = typeof window === 'undefined' ? require('html-element') : window
var document = w.document
var Text = w.Text
function context () {
var cleanupFuncs = []
function h() {
var args = [].slice.call(arguments), e = null
function item (l) {
var r
function parseClass (string) {
// Our minimal parser doesn’t understand escaping CSS special
// characters like `#`. Don’t use them. More reading:
// https://mathiasbynens.be/notes/css-escapes .
var m = split(string, /([\.#]?[^\s#.]+)/)
if(/^\.|#/.test(m[1]))
e = document.createElement('div')
forEach(m, function (v) {
var s = v.substring(1,v.length)
if(!v) return
if(!e)
e = document.createElement(v)
else if (v[0] === '.')
ClassList(e).add(s)
else if (v[0] === '#')
e.setAttribute('id', s)
})
}
if(l == null)
;
else if('string' === typeof l) {
if(!e)
parseClass(l)
else
e.appendChild(r = document.createTextNode(l))
}
else if('number' === typeof l
|| 'boolean' === typeof l
|| l instanceof Date
|| l instanceof RegExp ) {
e.appendChild(r = document.createTextNode(l.toString()))
}
//there might be a better way to handle this...
else if (isArray(l))
forEach(l, item)
else if(isNode(l))
e.appendChild(r = l)
else if(l instanceof Text)
e.appendChild(r = l)
else if ('object' === typeof l) {
for (var k in l) {
if('function' === typeof l[k]) {
if(/^on\w+/.test(k)) {
(function (k, l) { // capture k, l in the closure
if (e.addEventListener){
e.addEventListener(k.substring(2), l[k], false)
cleanupFuncs.push(function(){
e.removeEventListener(k.substring(2), l[k], false)
})
}else{
e.attachEvent(k, l[k])
cleanupFuncs.push(function(){
e.detachEvent(k, l[k])
})
}
})(k, l)
} else {
// observable
e[k] = l[k]()
cleanupFuncs.push(l[k](function (v) {
e[k] = v
}))
}
}
else if(k === 'style') {
if('string' === typeof l[k]) {
e.style.cssText = l[k]
}else{
for (var s in l[k]) (function(s, v) {
if('function' === typeof v) {
// observable
e.style.setProperty(s, v())
cleanupFuncs.push(v(function (val) {
e.style.setProperty(s, val)
}))
} else
var match = l[k][s].match(/(.*)\W+!important\W*$/);
if (match) {
e.style.setProperty(s, match[1], 'important')
} else {
e.style.setProperty(s, l[k][s])
}
})(s, l[k][s])
}
} else if(k === 'attrs') {
for (var v in l[k]) {
e.setAttribute(v, l[k][v])
}
}
else if (k.substr(0, 5) === "data-") {
e.setAttribute(k, l[k])
} else {
e[k] = l[k]
}
}
} else if ('function' === typeof l) {
//assume it's an observable!
var v = l()
e.appendChild(r = isNode(v) ? v : document.createTextNode(v))
cleanupFuncs.push(l(function (v) {
if(isNode(v) && r.parentElement)
r.parentElement.replaceChild(v, r), r = v
else
r.textContent = v
}))
}
return r
}
while(args.length)
item(args.shift())
return e
}
h.cleanup = function () {
for (var i = 0; i < cleanupFuncs.length; i++){
cleanupFuncs[i]()
}
cleanupFuncs.length = 0
}
return h
}
var h = module.exports = context()
h.context = context
function isNode (el) {
return el && el.nodeName && el.nodeType
}
function forEach (arr, fn) {
if (arr.forEach) return arr.forEach(fn)
for (var i = 0; i < arr.length; i++) fn(arr[i], i)
}
function isArray (arr) {
return Object.prototype.toString.call(arr) == '[object Array]'
}
},{"browser-split":5,"class-list":9,"html-element":4}],323:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],324:[function(require,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}],325:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],326:[function(require,module,exports){
var containers = []; // will store container HTMLElement references
var styleElements = []; // will store {prepend: HTMLElement, append: HTMLElement}
var usage = 'insert-css: You need to provide a CSS string. Usage: insertCss(cssString[, options]).';
function insertCss(css, options) {
options = options || {};
if (css === undefined) {
throw new Error(usage);
}
var position = options.prepend === true ? 'prepend' : 'append';
var container = options.container !== undefined ? options.container : document.querySelector('head');
var containerId = containers.indexOf(container);
// first time we see this container, create the necessary entries
if (containerId === -1) {
containerId = containers.push(container) - 1;
styleElements[containerId] = {};
}
// try to get the correponding container + position styleElement, create it otherwise
var styleElement;
if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) {
styleElement = styleElements[containerId][position];
} else {
styleElement = styleElements[containerId][position] = createStyleElement();
if (position === 'prepend') {
container.insertBefore(styleElement, container.childNodes[0]);
} else {
container.appendChild(styleElement);
}
}
// strip potential UTF-8 BOM if css was read from a file
if (css.charCodeAt(0) === 0xFEFF) { css = css.substr(1, css.length); }
// actually add the stylesheet
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText += css
} else {
styleElement.textContent += css;
}
return styleElement;
};
function createStyleElement() {
var styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
return styleElement;
}
module.exports = insertCss;
module.exports.insertCss = insertCss;
},{}],327:[function(require,module,exports){
/*! npm.im/intervalometer */
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function intervalometer(cb, request, cancel, requestParameter) {
var requestId;
var previousLoopTime;
function loop(now) {
// must be requested before cb() because that might call .stop()
requestId = request(loop, requestParameter);
// called with "ms since last call". 0 on start()
cb(now - (previousLoopTime || now));
previousLoopTime = now;
}
return {
start: function start() {
if (!requestId) { // prevent double starts
loop(0);
}
},
stop: function stop() {
cancel(requestId);
requestId = null;
previousLoopTime = 0;
}
};
}
function frameIntervalometer(cb) {
return intervalometer(cb, requestAnimationFrame, cancelAnimationFrame);
}
function timerIntervalometer(cb, delay) {
return intervalometer(cb, setTimeout, clearTimeout, delay);
}
exports.intervalometer = intervalometer;
exports.frameIntervalometer = frameIntervalometer;
exports.timerIntervalometer = timerIntervalometer;
},{}],328:[function(require,module,exports){
/*! npm.im/iphone-inline-video 2.0.2 */
'use strict';
var intervalometer = require('intervalometer');
function preventEvent(element, eventName, toggleProperty, preventWithProperty) {
function handler(e) {
if (Boolean(element[toggleProperty]) === Boolean(preventWithProperty)) {
e.stopImmediatePropagation();
// console.log(eventName, 'prevented on', element);
}
delete element[toggleProperty];
}
element.addEventListener(eventName, handler, false);
// Return handler to allow to disable the prevention. Usage:
// const preventionHandler = preventEvent(el, 'click');
// el.removeEventHandler('click', preventionHandler);
return handler;
}
function proxyProperty(object, propertyName, sourceObject, copyFirst) {
function get() {
return sourceObject[propertyName];
}
function set(value) {
sourceObject[propertyName] = value;
}
if (copyFirst) {
set(object[propertyName]);
}
Object.defineProperty(object, propertyName, {get: get, set: set});
}
function proxyEvent(object, eventName, sourceObject) {
sourceObject.addEventListener(eventName, function () { return object.dispatchEvent(new Event(eventName)); });
}
function dispatchEventAsync(element, type) {
Promise.resolve().then(function () {
element.dispatchEvent(new Event(type));
});
}
var iOS8or9 = typeof document === 'object' && 'object-fit' in document.head.style && !matchMedia('(-webkit-video-playable-inline)').matches;
var ಠ = 'bfred-it:iphone-inline-video';
var ಠevent = 'bfred-it:iphone-inline-video:event';
var ಠplay = 'bfred-it:iphone-inline-video:nativeplay';
var ಠpause = 'bfred-it:iphone-inline-video:nativepause';
/**
* UTILS
*/
function getAudioFromVideo(video) {
var audio = new Audio();
proxyEvent(video, 'play', audio);
proxyEvent(video, 'playing', audio);
proxyEvent(video, 'pause', audio);
audio.crossOrigin = video.crossOrigin;
// 'data:' causes audio.networkState > 0
// which then allows to keep <audio> in a resumable playing state
// i.e. once you set a real src it will keep playing if it was if .play() was called
audio.src = video.src || video.currentSrc || 'data:';
// if (audio.src === 'data:') {
// TODO: wait for video to be selected
// }
return audio;
}
var lastRequests = [];
var requestIndex = 0;
var lastTimeupdateEvent;
function setTime(video, time, rememberOnly) {
// allow one timeupdate event every 200+ ms
if ((lastTimeupdateEvent || 0) + 200 < Date.now()) {
video[ಠevent] = true;
lastTimeupdateEvent = Date.now();
}
if (!rememberOnly) {
video.currentTime = time;
}
lastRequests[++requestIndex % 3] = time * 100 | 0 / 100;
}
function isPlayerEnded(player) {
return player.driver.currentTime >= player.video.duration;
}
function update(timeDiff) {
var player = this;
// console.log('update', player.video.readyState, player.video.networkState, player.driver.readyState, player.driver.networkState, player.driver.paused);
if (player.video.readyState >= player.video.HAVE_FUTURE_DATA) {
if (!player.hasAudio) {
player.driver.currentTime = player.video.currentTime + ((timeDiff * player.video.playbackRate) / 1000);
if (player.video.loop && isPlayerEnded(player)) {
player.driver.currentTime = 0;
}
}
setTime(player.video, player.driver.currentTime);
} else if (player.video.networkState === player.video.NETWORK_IDLE && player.video.buffered.length === 0) {
// this should happen when the source is available but:
// - it's potentially playing (.paused === false)
// - it's not ready to play
// - it's not loading
// If it hasAudio, that will be loaded in the 'emptied' handler below
player.video.load();
// console.log('Will load');
}
// console.assert(player.video.currentTime === player.driver.currentTime, 'Video not updating!');
if (player.video.ended) {
delete player.video[ಠevent]; // allow timeupdate event
player.video.pause(true);
}
}
/**
* METHODS
*/
function play() {
// console.log('play');
var video = this;
var player = video[ಠ];
// if it's fullscreen, use the native player
if (video.webkitDisplayingFullscreen) {
video[ಠplay]();
return;
}
if (player.driver.src !== 'data:' && player.driver.src !== video.src) {
// console.log('src changed on play', video.src);
setTime(video, 0, true);
player.driver.src = video.src;
}
if (!video.paused) {
return;
}
player.paused = false;
if (video.buffered.length === 0) {
// .load() causes the emptied event
// the alternative is .play()+.pause() but that triggers play/pause events, even worse
// possibly the alternative is preventing this event only once
video.load();
}
player.driver.play();
player.updater.start();
if (!player.hasAudio) {
dispatchEventAsync(video, 'play');
if (player.video.readyState >= player.video.HAVE_ENOUGH_DATA) {
// console.log('onplay');
dispatchEventAsync(video, 'playing');
}
}
}
function pause(forceEvents) {
// console.log('pause');
var video = this;
var player = video[ಠ];
player.driver.pause();
player.updater.stop();
// if it's fullscreen, the developer the native player.pause()
// This is at the end of pause() because it also
// needs to make sure that the simulation is paused
if (video.webkitDisplayingFullscreen) {
video[ಠpause]();
}
if (player.paused && !forceEvents) {
return;
}
player.paused = true;
if (!player.hasAudio) {
dispatchEventAsync(video, 'pause');
}
if (video.ended) {
video[ಠevent] = true;
dispatchEventAsync(video, 'ended');
}
}
/**
* SETUP
*/
function addPlayer(video, hasAudio) {
var player = video[ಠ] = {};
player.paused = true; // track whether 'pause' events have been fired
player.hasAudio = hasAudio;
player.video = video;
player.updater = intervalometer.frameIntervalometer(update.bind(player));
if (hasAudio) {
player.driver = getAudioFromVideo(video);
} else {
video.addEventListener('canplay', function () {
if (!video.paused) {
// console.log('oncanplay');
dispatchEventAsync(video, 'playing');
}
});
player.driver = {
src: video.src || video.currentSrc || 'data:',
muted: true,
paused: true,
pause: function () {
player.driver.paused = true;
},
play: function () {
player.driver.paused = false;
// media automatically goes to 0 if .play() is called when it's done
if (isPlayerEnded(player)) {
setTime(video, 0);
}
},
get ended() {
return isPlayerEnded(player);
}
};
}
// .load() causes the emptied event
video.addEventListener('emptied', function () {
// console.log('driver src is', player.driver.src);
var wasEmpty = !player.driver.src || player.driver.src === 'data:';
if (player.driver.src && player.driver.src !== video.src) {
// console.log('src changed to', video.src);
setTime(video, 0, true);
player.driver.src = video.src;
// playing videos will only keep playing if no src was present when .play()’ed
if (wasEmpty) {
player.driver.play();
} else {
player.updater.stop();
}
}
}, false);
// stop programmatic player when OS takes over
video.addEventListener('webkitbeginfullscreen', function () {
if (!video.paused) {
// make sure that the <audio> and the syncer/updater are stopped
video.pause();
// play video natively
video[ಠplay]();
} else if (hasAudio && player.driver.buffered.length === 0) {
// if the first play is native,
// the <audio> needs to be buffered manually
// so when the fullscreen ends, it can be set to the same current time
player.driver.load();
}
});
if (hasAudio) {
video.addEventListener('webkitendfullscreen', function () {
// sync audio to new video position
player.driver.currentTime = video.currentTime;
// console.assert(player.driver.currentTime === video.currentTime, 'Audio not synced');
});
// allow seeking
video.addEventListener('seeking', function () {
if (lastRequests.indexOf(video.currentTime * 100 | 0 / 100) < 0) {
// console.log('User-requested seeking');
player.driver.currentTime = video.currentTime;
}
});
}
}
function overloadAPI(video) {
var player = video[ಠ];
video[ಠplay] = video.play;
video[ಠpause] = video.pause;
video.play = play;
video.pause = pause;
proxyProperty(video, 'paused', player.driver);
proxyProperty(video, 'muted', player.driver, true);
proxyProperty(video, 'playbackRate', player.driver, true);
proxyProperty(video, 'ended', player.driver);
proxyProperty(video, 'loop', player.driver, true);
preventEvent(video, 'seeking');
preventEvent(video, 'seeked');
preventEvent(video, 'timeupdate', ಠevent, false);
preventEvent(video, 'ended', ಠevent, false); // prevent occasional native ended events
}
function enableInlineVideo(video, opts) {
if ( opts === void 0 ) opts = {};
// Stop if already enabled
if (video[ಠ]) {
return;
}
// Allow the user to skip detection
if (!opts.everywhere) {
// Only iOS8 and 9 are supported
if (!iOS8or9) {
return;
}
// Stop if it's not an allowed device
if (!(opts.iPad || opts.ipad ? /iPhone|iPod|iPad/ : /iPhone|iPod/).test(navigator.userAgent)) {
return;
}
}
// Stop native playback
if (!video.paused && video.webkitDisplayingFullscreen) {
video.pause();
}
addPlayer(video, !video.muted);
overloadAPI(video);
video.classList.add('IIV');
// Autoplay
if (video.muted && video.autoplay) {
video.play();
}
if (!/iPhone|iPod|iPad/.test(navigator.platform)) {
console.warn('iphone-inline-video is not guaranteed to work in emulated environments');
}
}
module.exports = enableInlineVideo;
},{"intervalometer":327}],329:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],330:[function(require,module,exports){
'use strict';
var numberIsNan = require('number-is-nan');
module.exports = Number.isFinite || function (val) {
return !(typeof val !== 'number' || numberIsNan(val) || val === Infinity || val === -Infinity);
};
},{"number-is-nan":337}],331:[function(require,module,exports){
module.exports = isPowerOfTwo
function isPowerOfTwo(n) {
return n !== 0 && (n & (n - 1)) === 0
}
},{}],332:[function(require,module,exports){
module.exports = isTypedArray
isTypedArray.strict = isStrictTypedArray
isTypedArray.loose = isLooseTypedArray
var toString = Object.prototype.toString
var names = {
'[object Int8Array]': true
, '[object Int16Array]': true
, '[object Int32Array]': true
, '[object Uint8Array]': true
, '[object Uint8ClampedArray]': true
, '[object Uint16Array]': true
, '[object Uint32Array]': true
, '[object Float32Array]': true
, '[object Float64Array]': true
}
function isTypedArray(arr) {
return (
isStrictTypedArray(arr)
|| isLooseTypedArray(arr)
)
}
function isStrictTypedArray(arr) {
return (
arr instanceof Int8Array
|| arr instanceof Int16Array
|| arr instanceof Int32Array
|| arr instanceof Uint8Array
|| arr instanceof Uint8ClampedArray
|| arr instanceof Uint16Array
|| arr instanceof Uint32Array
|| arr instanceof Float32Array
|| arr instanceof Float64Array
)
}
function isLooseTypedArray(arr) {
return names[toString.call(arr)]
}
},{}],333:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],334:[function(require,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
"use strict";
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function(obj) {
var ret = {};
var key;
if (!(obj instanceof Object && !Array.isArray(obj))) {
throw new Error('keyMirror(...): Argument must be an object.');
}
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{}],335:[function(require,module,exports){
// Flat merge
module.exports = exports = function(host) {
var donors = slice(arguments, 1);
donors.forEach(function(donor) {
Object.keys(donor).forEach(function(key) {
host[key] = donor[key];
});
});
return host;
};
// Flat, selective merge
exports.selective = function(keys, host) {
var donors = slice(arguments, 1);
donors.forEach(function(donor) {
keys.forEach(function(key) {
host[key] = donor[key];
});
});
return host;
};
// Recursive merge
exports.recursive = function(host) {
var donors = slice(arguments, 1);
donors.forEach(function(donor) {
Object.keys(donor).forEach(recurser(host, donor));
});
return host;
};
// Recursive, selective merge
exports.selective.recursive = function(keys, host) {
var donors = slice(arguments, 1);
donors.forEach(function(donor) {
keys.forEach(recurser(host, donor));
});
return host;
};
// Helpers
function slice(arr, i) {
return Array.prototype.slice.call(arr, i);
}
function isObj(value) {
return !! (typeof value === 'object' && value);
}
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
function recurser(host, donor) {
return function(key) {
if (isObj(donor[key])) {
if (isObj(host[key])) {
exports.recursive(host[key], donor[key]);
} else {
var base = Array.isArray(donor[key]) ? [ ] : { };
host[key] = exports.recursive(base, donor[key]);
}
} else {
host[key] = donor[key];
}
};
}
/* End of file index.js */
/* Location: ./lib/index.js */
},{}],336:[function(require,module,exports){
'use strict';
var numberIsFinite = require('is-finite');
module.exports = Number.isInteger || function (x) {
return numberIsFinite(x) && Math.floor(x) === x;
};
},{"is-finite":330}],337:[function(require,module,exports){
'use strict';
module.exports = Number.isNaN || function (x) {
return x !== x;
};
},{}],338:[function(require,module,exports){
(function (process){
'use strict';
if (!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = nextTick;
} else {
module.exports = process.nextTick;
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this,require('_process'))
},{"_process":339}],339:[function(require,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.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
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; };
},{}],340:[function(require,module,exports){
(function (global){
var now = require('performance-now')
, root = typeof window === 'undefined' ? global : window
, vendors = ['moz', 'webkit']
, suffix = 'AnimationFrame'
, raf = root['request' + suffix]
, caf = root['cancel' + suffix] || root['cancelRequest' + suffix]
for(var i = 0; !raf && i < vendors.length; i++) {
raf = root[vendors[i] + 'Request' + suffix]
caf = root[vendors[i] + 'Cancel' + suffix]
|| root[vendors[i] + 'CancelRequest' + suffix]
}
// Some versions of FF have rAF but not cAF
if(!raf || !caf) {
var last = 0
, id = 0
, queue = []
, frameDuration = 1000 / 60
raf = function(callback) {
if(queue.length === 0) {
var _now = now()
, next = Math.max(0, frameDuration - (_now - last))
last = next + _now
setTimeout(function() {
var cp = queue.slice(0)
// Clear queue here to prevent
// callbacks from appending listeners
// to the current frame's queue
queue.length = 0
for(var i = 0; i < cp.length; i++) {
if(!cp[i].cancelled) {
try{
cp[i].callback(last)
} catch(e) {
setTimeout(function() { throw e }, 0)
}
}
}
}, Math.round(next))
}
queue.push({
handle: ++id,
callback: callback,
cancelled: false
})
return id
}
caf = function(handle) {
for(var i = 0; i < queue.length; i++) {
if(queue[i].handle === handle) {
queue[i].cancelled = true
}
}
}
}
module.exports = function(fn) {
// Wrap in a new function to prevent
// `cancel` potentially being assigned
// to the native rAF function
return raf.call(root, fn)
}
module.exports.cancel = function() {
caf.apply(root, arguments)
}
module.exports.polyfill = function() {
root.requestAnimationFrame = raf
root.cancelAnimationFrame = caf
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"performance-now":341}],341:[function(require,module,exports){
(function (process){
// Generated by CoffeeScript 1.12.2
(function() {
var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
module.exports = function() {
return performance.now();
};
} else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
module.exports = function() {
return (getNanoSeconds() - nodeLoadTime) / 1e6;
};
hrtime = process.hrtime;
getNanoSeconds = function() {
var hr;
hr = hrtime();
return hr[0] * 1e9 + hr[1];
};
moduleLoadTime = getNanoSeconds();
upTime = process.uptime() * 1e9;
nodeLoadTime = moduleLoadTime - upTime;
} else if (Date.now) {
module.exports = function() {
return Date.now() - loadTime;
};
loadTime = Date.now();
} else {
module.exports = function() {
return new Date().getTime() - loadTime;
};
loadTime = new Date().getTime();
}
}).call(this);
}).call(this,require('_process'))
},{"_process":339}],342:[function(require,module,exports){
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
},{"./_stream_readable":344,"./_stream_writable":346,"core-util-is":304,"inherits":325,"process-nextick-args":338}],343:[function(require,module,exports){
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":345,"core-util-is":304,"inherits":325}],344:[function(require,module,exports){
(function (process){
'use strict';
module.exports = Readable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') {
return emitter.prependListener(event, fn);
} else {
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
}
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options && typeof options.read === 'function') this._read = options.read;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
if (!state.objectMode && typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = bufferShim.from(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var _e = new Error('stream.unshift() after end event');
stream.emit('error', _e);
} else {
var skipAdd;
if (state.decoder && !addToFront && !encoding) {
chunk = state.decoder.write(chunk);
skipAdd = !state.objectMode && chunk.length === 0;
}
if (!addToFront) state.reading = false;
// Don't add to the buffer if we've decoded to an empty string chunk and
// we're not in object mode
if (!skipAdd) {
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
processNextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
processNextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
processNextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) self.push(chunk);
}
self.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = bufferShim.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
processNextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":342,"./internal/streams/BufferList":347,"./internal/streams/stream":348,"_process":339,"buffer":7,"buffer-shims":6,"core-util-is":304,"events":314,"inherits":325,"isarray":333,"process-nextick-args":338,"string_decoder/":349,"util":4}],345:[function(require,module,exports){
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
this.writeencoding = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined) stream.push(data);
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(this);
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.once('prefinish', function () {
if (typeof this._flush === 'function') this._flush(function (er, data) {
done(stream, er, data);
});else done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data !== null && data !== undefined) stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length) throw new Error('Calling transform done when ws.length != 0');
if (ts.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":342,"core-util-is":304,"inherits":325}],346:[function(require,module,exports){
(function (process){
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
module.exports = Writable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
util.inherits(Writable, Stream);
function nop() {}
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
processNextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
processNextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = Buffer.isBuffer(chunk);
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = bufferShim.from(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk)) encoding = 'buffer';
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) processNextTick(cb, er);else cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
while (entry) {
buffer[count] = entry;
entry = entry.next;
count += 1;
}
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequestCount = 0;
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else {
prefinish(stream, state);
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) processNextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function (err) {
var entry = _this.entry;
_this.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = _this;
} else {
state.corkedRequestsFree = _this;
}
};
}
}).call(this,require('_process'))
},{"./_stream_duplex":342,"./internal/streams/stream":348,"_process":339,"buffer":7,"buffer-shims":6,"core-util-is":304,"inherits":325,"process-nextick-args":338,"util-deprecate":365}],347:[function(require,module,exports){
'use strict';
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
module.exports = BufferList;
function BufferList() {
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function (v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function (v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function () {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function () {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function (s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function (n) {
if (this.length === 0) return bufferShim.alloc(0);
if (this.length === 1) return this.head.data;
var ret = bufferShim.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
p.data.copy(ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
},{"buffer":7,"buffer-shims":6}],348:[function(require,module,exports){
module.exports = require('events').EventEmitter;
},{"events":314}],349:[function(require,module,exports){
'use strict';
var Buffer = require('buffer').Buffer;
var bufferShim = require('buffer-shims');
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = bufferShim.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return -1;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd'.repeat(p);
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd'.repeat(p + 1);
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd'.repeat(p + 2);
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character for each buffered byte of a (partial)
// character needs to be added to the output.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
},{"buffer":7,"buffer-shims":6}],350:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":342,"./lib/_stream_passthrough.js":343,"./lib/_stream_readable.js":344,"./lib/_stream_transform.js":345,"./lib/_stream_writable.js":346}],351:[function(require,module,exports){
'use strict';
var readystate = module.exports = require('./readystate')
, win = (new Function('return this'))()
, complete = 'complete'
, root = true
, doc = win.document
, html = doc.documentElement;
(function wrapper() {
//
// Bail out early if the document is already fully loaded. This means that this
// script is loaded after the onload event.
//
if (complete === doc.readyState) {
return readystate.change(complete);
}
//
// Use feature detection to see what kind of browser environment we're dealing
// with. Old versions of Internet Explorer do not support the addEventListener
// interface so we can also safely assume that we need to fall back to polling.
//
var modern = !!doc.addEventListener
, prefix = modern ? '' : 'on'
, on = modern ? 'addEventListener' : 'attachEvent'
, off = modern ? 'removeEventListener' : 'detachEvent';
if (!modern && 'function' === typeof html.doScroll) {
try { root = !win.frameElement; }
catch (e) {}
if (root) (function polling() {
try { html.doScroll('left'); }
catch (e) { return setTimeout(polling, 50); }
readystate.change('interactive');
}());
}
/**
* Handle the various of event listener calls.
*
* @param {Event} evt Simple DOM event.
* @api private
*/
function change(evt) {
evt = evt || win.event;
if ('readystatechange' === evt.type) {
readystate.change(doc.readyState);
if (complete !== doc.readyState) return;
}
if ('load' === evt.type) readystate.change('complete');
else readystate.change('interactive');
//
// House keeping, remove our assigned event listeners.
//
(evt.type === 'load' ? win : doc)[off](evt.type, change, false);
}
//
// Assign a shit load of event listeners so we can update our internal state.
//
doc[on](prefix +'DOMContentLoaded', change, false);
doc[on](prefix +'readystatechange', change, false);
win[on](prefix +'load', change, false);
} ());
},{"./readystate":352}],352:[function(require,module,exports){
'use strict';
/**
* Generate a new prototype method which will the given function once the
* desired state has been reached. The returned function accepts 2 arguments:
*
* - fn: The assigned function which needs to be called.
* - context: Context/this value of the function we need to execute.
*
* @param {String} state The state we need to operate upon.
* @returns {Function}
* @api private
*/
function generate(state) {
return function proxy(fn, context) {
var rs = this;
if (rs.is(state)) {
setTimeout(function () {
fn.call(context, rs.readyState);
}, 0);
} else {
if (!rs._events[state]) rs._events[state] = [];
rs._events[state].push({ fn: fn, context: context });
}
return rs;
};
}
/**
* RS (readyState) instance.
*
* @constructor
* @api public
*/
function RS() {
this.readyState = RS.UNKNOWN;
this._events = {};
}
/**
* The environment can be in different states. The following states are
* generated:
*
* - ALL: The I don't really give a fuck state.
* - UNKNOWN: We got an unknown readyState we should start listening for events.
* - LOADING: Environment is currently loading.
* - INTERACTIVE: Environment is ready for modification.
* - COMPLETE: All resources have been loaded.
*
* Please note that the order of the `states` string/array is of vital
* importance as it's used in the readyState check.
*
* @type {Number}
* @private
*/
RS.states = 'ALL,UNKNOWN,LOADING,INTERACTIVE,COMPLETE'.split(',');
for (var s = 0, state; s < RS.states.length; s++) {
state = RS.states[s];
RS[state] = RS.prototype[state] = s;
RS.prototype[state.toLowerCase()] = generate(state);
}
/**
* A change in the environment has been detected so we need to change our
* readyState and call assigned event listeners and those of the previous
* states.
*
* @param {Number} state The new readyState that we detected.
* @returns {RS}
* @api private
*/
RS.prototype.change = function change(state) {
state = this.clean(state, true);
var j
, name
, i = 0
, listener
, rs = this
, previously = rs.readyState;
if (previously >= state) return rs;
rs.readyState = state;
for (; i < RS.states.length; i++) {
if (i > state) break;
name = RS.states[i];
if (name in rs._events) {
for (j = 0; j < rs._events[name].length; j++) {
listener = rs._events[name][j];
listener.fn.call(listener.context || rs, previously);
}
delete rs._events[name];
}
}
return rs;
};
/**
* Check if we're currently in a given readyState.
*
* @param {String|Number} state The required readyState.
* @returns {Boolean} Indication if this state has been reached.
* @api public
*/
RS.prototype.is = function is(state) {
return this.readyState >= this.clean(state, true);
};
/**
* Transform a state to a number or toUpperCase.
*
* @param {Mixed} state State to transform.
* @param {Boolean} nr Change to number.
* @returns {Mixed}
* @api public
*/
RS.prototype.clean = function transform(state, nr) {
var type = typeof state;
if (nr) return 'number' !== type
? +RS[state.toUpperCase()] || 0
: state;
return ('number' === type ? RS.states[state] : state).toUpperCase();
};
/**
* Removes all event listeners. Useful when you want to unload readystatechange
* completely so that it won't react to any events anymore. See
* https://github.com/unshiftio/readystate/issues/8
*
* @returns {Function} rs so that calls can be chained.
* @api public
*/
RS.prototype.removeAllListeners = function removeAllListeners() {
this._events = {};
return this;
}
//
// Expose the module.
//
module.exports = new RS();
},{}],353:[function(require,module,exports){
/**
* request-frame - requestAnimationFrame & cancelAnimationFrame polyfill for optimal cross-browser development.
* @version v1.5.3
* @license MIT
* Copyright Julien Etienne 2015 All Rights Reserved.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.requestFrame = factory());
}(this, (function () { 'use strict';
/**
* @param {String} type - request | cancel | native.
* @return {Function} Timing function.
*/
function requestFrame(type) {
// The only vendor prefixes required.
var vendors = ['moz', 'webkit'];
// Disassembled timing function abbreviations.
var aF = 'AnimationFrame';
var rqAF = 'Request' + aF;
// Checks for firefox 4 - 10 function pair mismatch.
var mozRAF = window.mozRequestAnimationFrame;
var mozCAF = window.mozCancelAnimationFrame;
var hasMozMismatch = mozRAF && !mozCAF;
// Final assigned functions.
var assignedRequestAnimationFrame;
var assignedCancelAnimationFrame;
// Initial time of the timing lapse.
var previousTime = 0;
var requestFrameMain;
// Date.now polyfill, mainly for legacy IE versions.
if (!Date.now) {
Date.now = function () {
return new Date().getTime();
};
}
/**
* hasIOS6RequestAnimationFrameBug.
* @See {@Link https://gist.github.com/julienetie/86ac394ec41f1271ff0a}
* - for Commentary.
* @Copyright 2015 - Julien Etienne.
* @License: MIT.
*/
function hasIOS6RequestAnimationFrameBug() {
var webkitRAF = window.webkitRequestAnimationFrame;
var rAF = window.requestAnimationFrame;
// CSS/ Device with max for iOS6 Devices.
var hasMobileDeviceWidth = screen.width <= 768 ? true : false;
// Only supports webkit prefixed requestAnimtionFrane.
var requiresWebkitprefix = !(webkitRAF && rAF);
// iOS6 webkit browsers don't support performance now.
var hasNoNavigationTiming = window.performance ? false : true;
var iOS6Notice = 'setTimeout is being used as a substitiue for \n requestAnimationFrame due to a bug within iOS 6 builds';
var hasIOS6Bug = requiresWebkitprefix && hasMobileDeviceWidth && hasNoNavigationTiming;
var bugCheckresults = function bugCheckresults(timingFnA, timingFnB, notice) {
if (timingFnA || timingFnB) {
console.warn(notice);
return true;
} else {
return false;
}
};
var displayResults = function displayResults(hasBug, hasBugNotice, webkitFn, nativeFn) {
if (hasBug) {
return bugCheckresults(webkitFn, nativeFn, hasBugNotice);
} else {
return false;
}
};
return displayResults(hasIOS6Bug, iOS6Notice, webkitRAF, rAF);
}
/**
* Native clearTimeout function.
* @return {Function}
*/
function clearTimeoutWithId(id) {
clearTimeout(id);
}
/**
* Based on a polyfill by Erik, introduced by Paul Irish &
* further improved by Darius Bacon.
* @see {@link http://www.paulirish.com/2011/
* requestanimationframe-for-smart-animating}
* @see {@link https://github.com/darius/requestAnimationFrame/blob/
* master/requestAnimationFrame.js}
* @callback {Number} Timestamp.
* @return {Function} setTimeout Function.
*/
function setTimeoutWithTimestamp(callback) {
var immediateTime = Date.now();
var lapsedTime = Math.max(previousTime + 16, immediateTime);
return setTimeout(function () {
callback(previousTime = lapsedTime);
}, lapsedTime - immediateTime);
}
/**
* Queries the native function, prefixed function
* or use the setTimeoutWithTimestamp function.
* @return {Function}
*/
function queryRequestAnimationFrame() {
if (Array.prototype.filter) {
assignedRequestAnimationFrame = window['request' + aF] || window[vendors.filter(function (vendor) {
if (window[vendor + rqAF] !== undefined) return vendor;
}) + rqAF] || setTimeoutWithTimestamp;
} else {
return setTimeoutWithTimestamp;
}
if (!hasIOS6RequestAnimationFrameBug()) {
return assignedRequestAnimationFrame;
} else {
return setTimeoutWithTimestamp;
}
}
/**
* Queries the native function, prefixed function
* or use the clearTimeoutWithId function.
* @return {Function}
*/
function queryCancelAnimationFrame() {
var cancellationNames = [];
if (Array.prototype.map) {
vendors.map(function (vendor) {
return ['Cancel', 'CancelRequest'].map(function (cancellationNamePrefix) {
cancellationNames.push(vendor + cancellationNamePrefix + aF);
});
});
} else {
return clearTimeoutWithId;
}
/**
* Checks for the prefixed cancelAnimationFrame implementation.
* @param {Array} prefixedNames - An array of the prefixed names.
* @param {Number} i - Iteration start point.
* @return {Function} prefixed cancelAnimationFrame function.
*/
function prefixedCancelAnimationFrame(prefixedNames, i) {
var cancellationFunction = void 0;
for (; i < prefixedNames.length; i++) {
if (window[prefixedNames[i]]) {
cancellationFunction = window[prefixedNames[i]];
break;
}
}
return cancellationFunction;
}
// Use truthly function
assignedCancelAnimationFrame = window['cancel' + aF] || prefixedCancelAnimationFrame(cancellationNames, 0) || clearTimeoutWithId;
// Check for iOS 6 bug
if (!hasIOS6RequestAnimationFrameBug()) {
return assignedCancelAnimationFrame;
} else {
return clearTimeoutWithId;
}
}
function getRequestFn() {
if (hasMozMismatch) {
return setTimeoutWithTimestamp;
} else {
return queryRequestAnimationFrame();
}
}
function getCancelFn() {
return queryCancelAnimationFrame();
}
function setNativeFn() {
if (hasMozMismatch) {
window.requestAnimationFrame = setTimeoutWithTimestamp;
window.cancelAnimationFrame = clearTimeoutWithId;
} else {
window.requestAnimationFrame = queryRequestAnimationFrame();
window.cancelAnimationFrame = queryCancelAnimationFrame();
}
}
/**
* The type value "request" singles out firefox 4 - 10 and
* assigns the setTimeout function if plausible.
*/
switch (type) {
case 'request':
case '':
requestFrameMain = getRequestFn();
break;
case 'cancel':
requestFrameMain = getCancelFn();
break;
case 'native':
setNativeFn();
break;
default:
throw new Error('RequestFrame parameter is not a type.');
}
return requestFrameMain;
}
return requestFrame;
})));
},{}],354:[function(require,module,exports){
module.exports = require('buffer')
},{"buffer":7}],355:[function(require,module,exports){
module.exports = shift
function shift (stream) {
var rs = stream._readableState
if (!rs) return null
return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
}
function getStateLength (state) {
if (state.buffer.length) {
// Since node 6.3.0 state.buffer is a BufferList not an array
if (state.buffer.head) {
return state.buffer.head.data.length
}
return state.buffer[0].length
}
return state.length
}
},{}],356:[function(require,module,exports){
/**
* Root reference for iframes.
*/
var root;
if (typeof window !== 'undefined') { // Browser window
root = window;
} else if (typeof self !== 'undefined') { // Web Worker
root = self;
} else { // Other environments
console.warn("Using browser-only version of superagent in non-browser environment");
root = this;
}
var Emitter = require('component-emitter');
var RequestBase = require('./request-base');
var isObject = require('./is-object');
var isFunction = require('./is-function');
var ResponseBase = require('./response-base');
var shouldRetry = require('./should-retry');
/**
* Noop.
*/
function noop(){};
/**
* Expose `request`.
*/
var request = exports = module.exports = function(method, url) {
// callback
if ('function' == typeof url) {
return new exports.Request('GET', method).end(url);
}
// url first
if (1 == arguments.length) {
return new exports.Request('GET', method);
}
return new exports.Request(method, url);
}
exports.Request = Request;
/**
* Determine XHR.
*/
request.getXHR = function () {
if (root.XMLHttpRequest
&& (!root.location || 'file:' != root.location.protocol
|| !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}
throw Error("Browser-only verison of superagent could not find XHR");
};
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function serialize(obj) {
if (!isObject(obj)) return obj;
var pairs = [];
for (var key in obj) {
pushEncodedKeyValuePair(pairs, key, obj[key]);
}
return pairs.join('&');
}
/**
* Helps 'serialize' with serializing arrays.
* Mutates the pairs array.
*
* @param {Array} pairs
* @param {String} key
* @param {Mixed} val
*/
function pushEncodedKeyValuePair(pairs, key, val) {
if (val != null) {
if (Array.isArray(val)) {
val.forEach(function(v) {
pushEncodedKeyValuePair(pairs, key, v);
});
} else if (isObject(val)) {
for(var subkey in val) {
pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);
}
} else {
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(val));
}
} else if (val === null) {
pairs.push(encodeURIComponent(key));
}
}
/**
* Expose serialization method.
*/
request.serializeObject = serialize;
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseString(str) {
var obj = {};
var pairs = str.split('&');
var pair;
var pos;
for (var i = 0, len = pairs.length; i < len; ++i) {
pair = pairs[i];
pos = pair.indexOf('=');
if (pos == -1) {
obj[decodeURIComponent(pair)] = '';
} else {
obj[decodeURIComponent(pair.slice(0, pos))] =
decodeURIComponent(pair.slice(pos + 1));
}
}
return obj;
}
/**
* Expose parser.
*/
request.parseString = parseString;
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
request.types = {
html: 'text/html',
json: 'application/json',
xml: 'application/xml',
urlencoded: 'application/x-www-form-urlencoded',
'form': 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
lines.pop(); // trailing CRLF
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
}
/**
* Check if `mime` is json or has +json structured syntax suffix.
*
* @param {String} mime
* @return {Boolean}
* @api private
*/
function isJSON(mime) {
return /[\/+]json\b/.test(mime);
}
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
function Response(req) {
this.req = req;
this.xhr = this.req.xhr;
// responseText is accessible only if responseType is '' or 'text' and on older browsers
this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
? this.xhr.responseText
: null;
this.statusText = this.req.xhr.statusText;
var status = this.xhr.status;
// handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
if (status === 1223) {
status = 204;
}
this._setStatusProperties(status);
this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
// getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
// getResponseHeader still works. so we get content-type even if getting
// other headers fails.
this.header['content-type'] = this.xhr.getResponseHeader('content-type');
this._setHeaderProperties(this.header);
if (null === this.text && req._responseType) {
this.body = this.xhr.response;
} else {
this.body = this.req.method != 'HEAD'
? this._parseBody(this.text ? this.text : this.xhr.response)
: null;
}
}
ResponseBase(Response.prototype);
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
Response.prototype._parseBody = function(str){
var parse = request.parse[this.type];
if(this.req._parser) {
return this.req._parser(this, str);
}
if (!parse && isJSON(this.type)) {
parse = request.parse['application/json'];
}
return parse && str && (str.length || str instanceof Object)
? parse(str)
: null;
};
/**
* Return an `Error` representative of this response.
*
* @return {Error}
* @api public
*/
Response.prototype.toError = function(){
var req = this.req;
var method = req.method;
var url = req.url;
var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
var err = new Error(msg);
err.status = this.status;
err.method = method;
err.url = url;
return err;
};
/**
* Expose `Response`.
*/
request.Response = Response;
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
function Request(method, url) {
var self = this;
this._query = this._query || [];
this.method = method;
this.url = url;
this.header = {}; // preserves header name case
this._header = {}; // coerces header names to lowercase
this.on('end', function(){
var err = null;
var res = null;
try {
res = new Response(self);
} catch(e) {
err = new Error('Parser is unable to parse the response');
err.parse = true;
err.original = e;
// issue #675: return the raw response if the response parsing fails
if (self.xhr) {
// ie9 doesn't have 'response' property
err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;
// issue #876: return the http status code if the response parsing fails
err.status = self.xhr.status ? self.xhr.status : null;
err.statusCode = err.status; // backwards-compat only
} else {
err.rawResponse = null;
err.status = null;
}
return self.callback(err);
}
self.emit('response', res);
var new_err;
try {
if (!self._isResponseOK(res)) {
new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
new_err.original = err;
new_err.response = res;
new_err.status = res.status;
}
} catch(e) {
new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android
}
// #1000 don't catch errors from the callback to avoid double calling it
if (new_err) {
self.callback(new_err, res);
} else {
self.callback(null, res);
}
});
}
/**
* Mixin `Emitter` and `RequestBase`.
*/
Emitter(Request.prototype);
RequestBase(Request.prototype);
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function(type){
this.set('Content-Type', request.types[type] || type);
return this;
};
/**
* Set Accept to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.json = 'application/json';
*
* request.get('/agent')
* .accept('json')
* .end(callback);
*
* request.get('/agent')
* .accept('application/json')
* .end(callback);
*
* @param {String} accept
* @return {Request} for chaining
* @api public
*/
Request.prototype.accept = function(type){
this.set('Accept', request.types[type] || type);
return this;
};
/**
* Set Authorization field value with `user` and `pass`.
*
* @param {String} user
* @param {String} [pass] optional in case of using 'bearer' as type
* @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
* @return {Request} for chaining
* @api public
*/
Request.prototype.auth = function(user, pass, options){
if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options
options = pass;
}
if (!options) {
options = {
type: 'function' === typeof btoa ? 'basic' : 'auto',
}
}
switch (options.type) {
case 'basic':
this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));
break;
case 'auto':
this.username = user;
this.password = pass;
break;
case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
this.set('Authorization', 'Bearer ' + user);
break;
}
return this;
};
/**
* Add query-string `val`.
*
* Examples:
*
* request.get('/shoes')
* .query('size=10')
* .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function(val){
if ('string' != typeof val) val = serialize(val);
if (val) this._query.push(val);
return this;
};
/**
* Queue the given `file` as an attachment to the specified `field`,
* with optional `options` (or filename).
*
* ``` js
* request.post('/upload')
* .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
* .end(callback);
* ```
*
* @param {String} field
* @param {Blob|File} file
* @param {String|Object} options
* @return {Request} for chaining
* @api public
*/
Request.prototype.attach = function(field, file, options){
if (file) {
if (this._data) {
throw Error("superagent can't mix .send() and .attach()");
}
this._getFormData().append(field, file, options || file.name);
}
return this;
};
Request.prototype._getFormData = function(){
if (!this._formData) {
this._formData = new root.FormData();
}
return this._formData;
};
/**
* Invoke the callback with `err` and `res`
* and handle arity check.
*
* @param {Error} err
* @param {Response} res
* @api private
*/
Request.prototype.callback = function(err, res){
// console.log(this._retries, this._maxRetries)
if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) {
return this._retry();
}
var fn = this._callback;
this.clearTimeout();
if (err) {
if (this._maxRetries) err.retries = this._retries - 1;
this.emit('error', err);
}
fn(err, res);
};
/**
* Invoke callback with x-domain error.
*
* @api private
*/
Request.prototype.crossDomainError = function(){
var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
err.crossDomain = true;
err.status = this.status;
err.method = this.method;
err.url = this.url;
this.callback(err);
};
// This only warns, because the request is still likely to work
Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){
console.warn("This is not supported in browser version of superagent");
return this;
};
// This throws, because it can't send/receive data as expected
Request.prototype.pipe = Request.prototype.write = function(){
throw Error("Streaming is not supported in browser version of superagent");
};
/**
* Compose querystring to append to req.url
*
* @api private
*/
Request.prototype._appendQueryString = function(){
var query = this._query.join('&');
if (query) {
this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;
}
if (this._sort) {
var index = this.url.indexOf('?');
if (index >= 0) {
var queryArr = this.url.substring(index + 1).split('&');
if (isFunction(this._sort)) {
queryArr.sort(this._sort);
} else {
queryArr.sort();
}
this.url = this.url.substring(0, index) + '?' + queryArr.join('&');
}
}
};
/**
* Check if `obj` is a host object,
* we don't want to serialize these :)
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
Request.prototype._isHost = function _isHost(obj) {
// Native objects stringify to [object File], [object Blob], [object FormData], etc.
return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
}
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
Request.prototype.end = function(fn){
if (this._endCalled) {
console.warn("Warning: .end() was called twice. This is not supported in superagent");
}
this._endCalled = true;
// store callback
this._callback = fn || noop;
// querystring
this._appendQueryString();
return this._end();
};
Request.prototype._end = function() {
var self = this;
var xhr = this.xhr = request.getXHR();
var data = this._formData || this._data;
this._setTimeouts();
// state change
xhr.onreadystatechange = function(){
var readyState = xhr.readyState;
if (readyState >= 2 && self._responseTimeoutTimer) {
clearTimeout(self._responseTimeoutTimer);
}
if (4 != readyState) {
return;
}
// In IE9, reads to any property (e.g. status) off of an aborted XHR will
// result in the error "Could not complete the operation due to error c00c023f"
var status;
try { status = xhr.status } catch(e) { status = 0; }
if (!status) {
if (self.timedout || self._aborted) return;
return self.crossDomainError();
}
self.emit('end');
};
// progress
var handleProgress = function(direction, e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
e.direction = direction;
self.emit('progress', e);
}
if (this.hasListeners('progress')) {
try {
xhr.onprogress = handleProgress.bind(null, 'download');
if (xhr.upload) {
xhr.upload.onprogress = handleProgress.bind(null, 'upload');
}
} catch(e) {
// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
// Reported here:
// https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
}
}
// initiate request
try {
if (this.username && this.password) {
xhr.open(this.method, this.url, true, this.username, this.password);
} else {
xhr.open(this.method, this.url, true);
}
} catch (err) {
// see #1149
return this.callback(err);
}
// CORS
if (this._withCredentials) xhr.withCredentials = true;
// body
if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {
// serialize stuff
var contentType = this._header['content-type'];
var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
if (!serialize && isJSON(contentType)) {
serialize = request.serialize['application/json'];
}
if (serialize) data = serialize(data);
}
// set header fields
for (var field in this.header) {
if (null == this.header[field]) continue;
if (this.header.hasOwnProperty(field))
xhr.setRequestHeader(field, this.header[field]);
}
if (this._responseType) {
xhr.responseType = this._responseType;
}
// send stuff
this.emit('request', this);
// IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
// We need null here if data is undefined
xhr.send(typeof data !== 'undefined' ? data : null);
return this;
};
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.get = function(url, data, fn){
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.query(data);
if (fn) req.end(fn);
return req;
};
/**
* HEAD `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.head = function(url, data, fn){
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* OPTIONS query to `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.options = function(url, data, fn){
var req = request('OPTIONS', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* DELETE `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} [data]
* @param {Function} [fn]
* @return {Request}
* @api public
*/
function del(url, data, fn){
var req = request('DELETE', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
request['del'] = del;
request['delete'] = del;
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} [data]
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.patch = function(url, data, fn){
var req = request('PATCH', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} [data]
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.post = function(url, data, fn){
var req = request('POST', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.put = function(url, data, fn){
var req = request('PUT', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
},{"./is-function":357,"./is-object":358,"./request-base":359,"./response-base":360,"./should-retry":361,"component-emitter":11}],357:[function(require,module,exports){
/**
* Check if `fn` is a function.
*
* @param {Function} fn
* @return {Boolean}
* @api private
*/
var isObject = require('./is-object');
function isFunction(fn) {
var tag = isObject(fn) ? Object.prototype.toString.call(fn) : '';
return tag === '[object Function]';
}
module.exports = isFunction;
},{"./is-object":358}],358:[function(require,module,exports){
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isObject(obj) {
return null !== obj && 'object' === typeof obj;
}
module.exports = isObject;
},{}],359:[function(require,module,exports){
/**
* Module of mixed-in functions shared between node and client code
*/
var isObject = require('./is-object');
/**
* Expose `RequestBase`.
*/
module.exports = RequestBase;
/**
* Initialize a new `RequestBase`.
*
* @api public
*/
function RequestBase(obj) {
if (obj) return mixin(obj);
}
/**
* Mixin the prototype properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in RequestBase.prototype) {
obj[key] = RequestBase.prototype[key];
}
return obj;
}
/**
* Clear previous timeout.
*
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.clearTimeout = function _clearTimeout(){
clearTimeout(this._timer);
clearTimeout(this._responseTimeoutTimer);
delete this._timer;
delete this._responseTimeoutTimer;
return this;
};
/**
* Override default response body parser
*
* This function will be called to convert incoming data into request.body
*
* @param {Function}
* @api public
*/
RequestBase.prototype.parse = function parse(fn){
this._parser = fn;
return this;
};
/**
* Set format of binary response body.
* In browser valid formats are 'blob' and 'arraybuffer',
* which return Blob and ArrayBuffer, respectively.
*
* In Node all values result in Buffer.
*
* Examples:
*
* req.get('/')
* .responseType('blob')
* .end(callback);
*
* @param {String} val
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.responseType = function(val){
this._responseType = val;
return this;
};
/**
* Override default request body serializer
*
* This function will be called to convert data set via .send or .attach into payload to send
*
* @param {Function}
* @api public
*/
RequestBase.prototype.serialize = function serialize(fn){
this._serializer = fn;
return this;
};
/**
* Set timeouts.
*
* - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
* - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
*
* Value of 0 or false means no timeout.
*
* @param {Number|Object} ms or {response, read, deadline}
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.timeout = function timeout(options){
if (!options || 'object' !== typeof options) {
this._timeout = options;
this._responseTimeout = 0;
return this;
}
for(var option in options) {
switch(option) {
case 'deadline':
this._timeout = options.deadline;
break;
case 'response':
this._responseTimeout = options.response;
break;
default:
console.warn("Unknown timeout option", option);
}
}
return this;
};
/**
* Set number of retry attempts on error.
*
* Failed requests will be retried 'count' times if timeout or err.code >= 500.
*
* @param {Number} count
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.retry = function retry(count){
// Default to 1 if no count passed or true
if (arguments.length === 0 || count === true) count = 1;
if (count <= 0) count = 0;
this._maxRetries = count;
this._retries = 0;
return this;
};
/**
* Retry request
*
* @return {Request} for chaining
* @api private
*/
RequestBase.prototype._retry = function() {
this.clearTimeout();
// node
if (this.req) {
this.req = null;
this.req = this.request();
}
this._aborted = false;
this.timedout = false;
return this._end();
};
/**
* Promise support
*
* @param {Function} resolve
* @param {Function} [reject]
* @return {Request}
*/
RequestBase.prototype.then = function then(resolve, reject) {
if (!this._fullfilledPromise) {
var self = this;
if (this._endCalled) {
console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises");
}
this._fullfilledPromise = new Promise(function(innerResolve, innerReject){
self.end(function(err, res){
if (err) innerReject(err); else innerResolve(res);
});
});
}
return this._fullfilledPromise.then(resolve, reject);
}
RequestBase.prototype.catch = function(cb) {
return this.then(undefined, cb);
};
/**
* Allow for extension
*/
RequestBase.prototype.use = function use(fn) {
fn(this);
return this;
}
RequestBase.prototype.ok = function(cb) {
if ('function' !== typeof cb) throw Error("Callback required");
this._okCallback = cb;
return this;
};
RequestBase.prototype._isResponseOK = function(res) {
if (!res) {
return false;
}
if (this._okCallback) {
return this._okCallback(res);
}
return res.status >= 200 && res.status < 300;
};
/**
* Get request header `field`.
* Case-insensitive.
*
* @param {String} field
* @return {String}
* @api public
*/
RequestBase.prototype.get = function(field){
return this._header[field.toLowerCase()];
};
/**
* Get case-insensitive header `field` value.
* This is a deprecated internal API. Use `.get(field)` instead.
*
* (getHeader is no longer used internally by the superagent code base)
*
* @param {String} field
* @return {String}
* @api private
* @deprecated
*/
RequestBase.prototype.getHeader = RequestBase.prototype.get;
/**
* Set header `field` to `val`, or multiple fields with one object.
* Case-insensitive.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.set = function(field, val){
if (isObject(field)) {
for (var key in field) {
this.set(key, field[key]);
}
return this;
}
this._header[field.toLowerCase()] = val;
this.header[field] = val;
return this;
};
/**
* Remove header `field`.
* Case-insensitive.
*
* Example:
*
* req.get('/')
* .unset('User-Agent')
* .end(callback);
*
* @param {String} field
*/
RequestBase.prototype.unset = function(field){
delete this._header[field.toLowerCase()];
delete this.header[field];
return this;
};
/**
* Write the field `name` and `val`, or multiple fields with one object
* for "multipart/form-data" request bodies.
*
* ``` js
* request.post('/upload')
* .field('foo', 'bar')
* .end(callback);
*
* request.post('/upload')
* .field({ foo: 'bar', baz: 'qux' })
* .end(callback);
* ```
*
* @param {String|Object} name
* @param {String|Blob|File|Buffer|fs.ReadStream} val
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.field = function(name, val) {
// name should be either a string or an object.
if (null === name || undefined === name) {
throw new Error('.field(name, val) name can not be empty');
}
if (this._data) {
console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
}
if (isObject(name)) {
for (var key in name) {
this.field(key, name[key]);
}
return this;
}
if (Array.isArray(val)) {
for (var i in val) {
this.field(name, val[i]);
}
return this;
}
// val should be defined now
if (null === val || undefined === val) {
throw new Error('.field(name, val) val can not be empty');
}
if ('boolean' === typeof val) {
val = '' + val;
}
this._getFormData().append(name, val);
return this;
};
/**
* Abort the request, and clear potential timeout.
*
* @return {Request}
* @api public
*/
RequestBase.prototype.abort = function(){
if (this._aborted) {
return this;
}
this._aborted = true;
this.xhr && this.xhr.abort(); // browser
this.req && this.req.abort(); // node
this.clearTimeout();
this.emit('abort');
return this;
};
/**
* Enable transmission of cookies with x-domain requests.
*
* Note that for this to work the origin must not be
* using "Access-Control-Allow-Origin" with a wildcard,
* and also must set "Access-Control-Allow-Credentials"
* to "true".
*
* @api public
*/
RequestBase.prototype.withCredentials = function(on){
// This is browser-only functionality. Node side is no-op.
if(on==undefined) on = true;
this._withCredentials = on;
return this;
};
/**
* Set the max redirects to `n`. Does noting in browser XHR implementation.
*
* @param {Number} n
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.redirects = function(n){
this._maxRedirects = n;
return this;
};
/**
* Convert to a plain javascript object (not JSON string) of scalar properties.
* Note as this method is designed to return a useful non-this value,
* it cannot be chained.
*
* @return {Object} describing method, url, and data of this request
* @api public
*/
RequestBase.prototype.toJSON = function(){
return {
method: this.method,
url: this.url,
data: this._data,
headers: this._header
};
};
/**
* Send `data` as the request body, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
* // manual json
* request.post('/user')
* .type('json')
* .send('{"name":"tj"}')
* .end(callback)
*
* // auto json
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
* // manual x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
* // auto x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
* // defaults to x-www-form-urlencoded
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.send = function(data){
var isObj = isObject(data);
var type = this._header['content-type'];
if (this._formData) {
console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
}
if (isObj && !this._data) {
if (Array.isArray(data)) {
this._data = [];
} else if (!this._isHost(data)) {
this._data = {};
}
} else if (data && this._data && this._isHost(this._data)) {
throw Error("Can't merge these send calls");
}
// merge
if (isObj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
} else if ('string' == typeof data) {
// default to x-www-form-urlencoded
if (!type) this.type('form');
type = this._header['content-type'];
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data
? this._data + '&' + data
: data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!isObj || this._isHost(data)) {
return this;
}
// default to json
if (!type) this.type('json');
return this;
};
/**
* Sort `querystring` by the sort function
*
*
* Examples:
*
* // default order
* request.get('/user')
* .query('name=Nick')
* .query('search=Manny')
* .sortQuery()
* .end(callback)
*
* // customized sort function
* request.get('/user')
* .query('name=Nick')
* .query('search=Manny')
* .sortQuery(function(a, b){
* return a.length - b.length;
* })
* .end(callback)
*
*
* @param {Function} sort
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.sortQuery = function(sort) {
// _sort default to true but otherwise can be a function or boolean
this._sort = typeof sort === 'undefined' ? true : sort;
return this;
};
/**
* Invoke callback with timeout error.
*
* @api private
*/
RequestBase.prototype._timeoutError = function(reason, timeout, errno){
if (this._aborted) {
return;
}
var err = new Error(reason + timeout + 'ms exceeded');
err.timeout = timeout;
err.code = 'ECONNABORTED';
err.errno = errno;
this.timedout = true;
this.abort();
this.callback(err);
};
RequestBase.prototype._setTimeouts = function() {
var self = this;
// deadline
if (this._timeout && !this._timer) {
this._timer = setTimeout(function(){
self._timeoutError('Timeout of ', self._timeout, 'ETIME');
}, this._timeout);
}
// response timeout
if (this._responseTimeout && !this._responseTimeoutTimer) {
this._responseTimeoutTimer = setTimeout(function(){
self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
}, this._responseTimeout);
}
}
},{"./is-object":358}],360:[function(require,module,exports){
/**
* Module dependencies.
*/
var utils = require('./utils');
/**
* Expose `ResponseBase`.
*/
module.exports = ResponseBase;
/**
* Initialize a new `ResponseBase`.
*
* @api public
*/
function ResponseBase(obj) {
if (obj) return mixin(obj);
}
/**
* Mixin the prototype properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in ResponseBase.prototype) {
obj[key] = ResponseBase.prototype[key];
}
return obj;
}
/**
* Get case-insensitive `field` value.
*
* @param {String} field
* @return {String}
* @api public
*/
ResponseBase.prototype.get = function(field){
return this.header[field.toLowerCase()];
};
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
ResponseBase.prototype._setHeaderProperties = function(header){
// TODO: moar!
// TODO: make this a util
// content-type
var ct = header['content-type'] || '';
this.type = utils.type(ct);
// params
var params = utils.params(ct);
for (var key in params) this[key] = params[key];
this.links = {};
// links
try {
if (header.link) {
this.links = utils.parseLinks(header.link);
}
} catch (err) {
// ignore
}
};
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
ResponseBase.prototype._setStatusProperties = function(status){
var type = status / 100 | 0;
// status / class
this.status = this.statusCode = status;
this.statusType = type;
// basics
this.info = 1 == type;
this.ok = 2 == type;
this.redirect = 3 == type;
this.clientError = 4 == type;
this.serverError = 5 == type;
this.error = (4 == type || 5 == type)
? this.toError()
: false;
// sugar
this.accepted = 202 == status;
this.noContent = 204 == status;
this.badRequest = 400 == status;
this.unauthorized = 401 == status;
this.notAcceptable = 406 == status;
this.forbidden = 403 == status;
this.notFound = 404 == status;
};
},{"./utils":362}],361:[function(require,module,exports){
var ERROR_CODES = [
'ECONNRESET',
'ETIMEDOUT',
'EADDRINFO',
'ESOCKETTIMEDOUT'
];
/**
* Determine if a request should be retried.
* (Borrowed from segmentio/superagent-retry)
*
* @param {Error} err
* @param {Response} [res]
* @returns {Boolean}
*/
module.exports = function shouldRetry(err, res) {
if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true;
if (res && res.status && res.status >= 500) return true;
// Superagent timeout
if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true;
if (err && 'crossDomain' in err) return true;
return false;
};
},{}],362:[function(require,module,exports){
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
exports.type = function(str){
return str.split(/ *; */).shift();
};
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
exports.params = function(str){
return str.split(/ *; */).reduce(function(obj, str){
var parts = str.split(/ *= */);
var key = parts.shift();
var val = parts.shift();
if (key && val) obj[key] = val;
return obj;
}, {});
};
/**
* Parse Link header fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
exports.parseLinks = function(str){
return str.split(/ *, */).reduce(function(obj, str){
var parts = str.split(/ *; */);
var url = parts[0].slice(1, -1);
var rel = parts[1].split(/ *= */)[1].slice(1, -1);
obj[rel] = url;
return obj;
}, {});
};
/**
* Strip content related fields from `header`.
*
* @param {Object} header
* @return {Object} header
* @api private
*/
exports.cleanHeader = function(header, shouldStripCookie){
delete header['content-type'];
delete header['content-length'];
delete header['transfer-encoding'];
delete header['host'];
if (shouldStripCookie) {
delete header['cookie'];
}
return header;
};
},{}],363:[function(require,module,exports){
(function (Buffer){
/**
* Convert a typed array to a Buffer without a copy
*
* Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* License: MIT
*
* `npm install typedarray-to-buffer`
*/
var isTypedArray = require('is-typedarray').strict
module.exports = function typedarrayToBuffer (arr) {
if (isTypedArray(arr)) {
// To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer
var buf = new Buffer(arr.buffer)
if (arr.byteLength !== arr.buffer.byteLength) {
// Respect the "view", i.e. byteOffset and byteLength, without doing a copy
buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)
}
return buf
} else {
// Pass through all other types to the `Buffer` constructor
return new Buffer(arr)
}
}
}).call(this,require("buffer").Buffer)
},{"buffer":7,"is-typedarray":332}],364:[function(require,module,exports){
/**
* UAParser.js v0.7.12
* Lightweight JavaScript-based User-Agent string parser
* https://github.com/faisalman/ua-parser-js
*
* Copyright © 2012-2016 Faisal Salman <fyzlman@gmail.com>
* Dual licensed under GPLv2 & MIT
*/
(function (window, undefined) {
'use strict';
//////////////
// Constants
/////////////
var LIBVERSION = '0.7.12',
EMPTY = '',
UNKNOWN = '?',
FUNC_TYPE = 'function',
UNDEF_TYPE = 'undefined',
OBJ_TYPE = 'object',
STR_TYPE = 'string',
MAJOR = 'major', // deprecated
MODEL = 'model',
NAME = 'name',
TYPE = 'type',
VENDOR = 'vendor',
VERSION = 'version',
ARCHITECTURE= 'architecture',
CONSOLE = 'console',
MOBILE = 'mobile',
TABLET = 'tablet',
SMARTTV = 'smarttv',
WEARABLE = 'wearable',
EMBEDDED = 'embedded';
///////////
// Helper
//////////
var util = {
extend : function (regexes, extensions) {
var margedRegexes = {};
for (var i in regexes) {
if (extensions[i] && extensions[i].length % 2 === 0) {
margedRegexes[i] = extensions[i].concat(regexes[i]);
} else {
margedRegexes[i] = regexes[i];
}
}
return margedRegexes;
},
has : function (str1, str2) {
if (typeof str1 === "string") {
return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
} else {
return false;
}
},
lowerize : function (str) {
return str.toLowerCase();
},
major : function (version) {
return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g,'').split(".")[0] : undefined;
},
trim : function (str) {
return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
}
};
///////////////
// Map helper
//////////////
var mapper = {
rgx : function () {
var result, i = 0, j, k, p, q, matches, match, args = arguments;
// loop through all regexes maps
while (i < args.length && !matches) {
var regex = args[i], // even sequence (0,2,4,..)
props = args[i + 1]; // odd sequence (1,3,5,..)
// construct object barebones
if (typeof result === UNDEF_TYPE) {
result = {};
for (p in props) {
if (props.hasOwnProperty(p)){
q = props[p];
if (typeof q === OBJ_TYPE) {
result[q[0]] = undefined;
} else {
result[q] = undefined;
}
}
}
}
// try matching uastring with regexes
j = k = 0;
while (j < regex.length && !matches) {
matches = regex[j++].exec(this.getUA());
if (!!matches) {
for (p = 0; p < props.length; p++) {
match = matches[++k];
q = props[p];
// check if given property is actually array
if (typeof q === OBJ_TYPE && q.length > 0) {
if (q.length == 2) {
if (typeof q[1] == FUNC_TYPE) {
// assign modified match
result[q[0]] = q[1].call(this, match);
} else {
// assign given value, ignore regex match
result[q[0]] = q[1];
}
} else if (q.length == 3) {
// check whether function or regex
if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
// call function (usually string mapper)
result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
} else {
// sanitize match using given regex
result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
}
} else if (q.length == 4) {
result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
}
} else {
result[q] = match ? match : undefined;
}
}
}
}
i += 2;
}
return result;
},
str : function (str, map) {
for (var i in map) {
// check if array
if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
for (var j = 0; j < map[i].length; j++) {
if (util.has(map[i][j], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
} else if (util.has(map[i], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
return str;
}
};
///////////////
// String map
//////////////
var maps = {
browser : {
oldsafari : {
version : {
'1.0' : '/8',
'1.2' : '/1',
'1.3' : '/3',
'2.0' : '/412',
'2.0.2' : '/416',
'2.0.3' : '/417',
'2.0.4' : '/419',
'?' : '/'
}
}
},
device : {
amazon : {
model : {
'Fire Phone' : ['SD', 'KF']
}
},
sprint : {
model : {
'Evo Shift 4G' : '7373KT'
},
vendor : {
'HTC' : 'APA',
'Sprint' : 'Sprint'
}
}
},
os : {
windows : {
version : {
'ME' : '4.90',
'NT 3.11' : 'NT3.51',
'NT 4.0' : 'NT4.0',
'2000' : 'NT 5.0',
'XP' : ['NT 5.1', 'NT 5.2'],
'Vista' : 'NT 6.0',
'7' : 'NT 6.1',
'8' : 'NT 6.2',
'8.1' : 'NT 6.3',
'10' : ['NT 6.4', 'NT 10.0'],
'RT' : 'ARM'
}
}
}
};
//////////////
// Regex map
/////////////
var regexes = {
browser : [[
// Presto based
/(opera\smini)\/([\w\.-]+)/i, // Opera Mini
/(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet
/(opera).+version\/([\w\.]+)/i, // Opera > 9.80
/(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80
], [NAME, VERSION], [
/(opios)[\/\s]+([\w\.]+)/i // Opera mini on iphone >= 8.0
], [[NAME, 'Opera Mini'], VERSION], [
/\s(opr)\/([\w\.]+)/i // Opera Webkit
], [[NAME, 'Opera'], VERSION], [
// Mixed
/(kindle)\/([\w\.]+)/i, // Kindle
/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,
// Lunascape/Maxthon/Netfront/Jasmine/Blazer
// Trident based
/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,
// Avant/IEMobile/SlimBrowser/Baidu
/(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer
// Webkit/KHTML based
/(rekonq)\/([\w\.]+)*/i, // Rekonq
/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs)\/([\w\.-]+)/i
// Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS
], [NAME, VERSION], [
/(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11
], [[NAME, 'IE'], VERSION], [
/(edge)\/((\d+)?[\w\.]+)/i // Microsoft Edge
], [NAME, VERSION], [
/(yabrowser)\/([\w\.]+)/i // Yandex
], [[NAME, 'Yandex'], VERSION], [
/(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon
], [[NAME, /_/g, ' '], VERSION], [
/(micromessenger)\/([\w\.]+)/i // WeChat
], [[NAME, 'WeChat'], VERSION], [
/xiaomi\/miuibrowser\/([\w\.]+)/i // MIUI Browser
], [VERSION, [NAME, 'MIUI Browser']], [
/\swv\).+(chrome)\/([\w\.]+)/i // Chrome WebView
], [[NAME, /(.+)/, '$1 WebView'], VERSION], [
/android.+samsungbrowser\/([\w\.]+)/i,
/android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i // Android Browser
], [VERSION, [NAME, 'Android Browser']], [
/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i,
// Chrome/OmniWeb/Arora/Tizen/Nokia
/(qqbrowser)[\/\s]?([\w\.]+)/i
// QQBrowser
], [NAME, VERSION], [
/(uc\s?browser)[\/\s]?([\w\.]+)/i,
/ucweb.+(ucbrowser)[\/\s]?([\w\.]+)/i,
/juc.+(ucweb)[\/\s]?([\w\.]+)/i
// UCBrowser
], [[NAME, 'UCBrowser'], VERSION], [
/(dolfin)\/([\w\.]+)/i // Dolphin
], [[NAME, 'Dolphin'], VERSION], [
/((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS
], [[NAME, 'Chrome'], VERSION], [
/;fbav\/([\w\.]+);/i // Facebook App for iOS
], [VERSION, [NAME, 'Facebook']], [
/fxios\/([\w\.-]+)/i // Firefox for iOS
], [VERSION, [NAME, 'Firefox']], [
/version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari
], [VERSION, [NAME, 'Mobile Safari']], [
/version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile
], [VERSION, NAME], [
/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0
], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [
/(konqueror)\/([\w\.]+)/i, // Konqueror
/(webkit|khtml)\/([\w\.]+)/i
], [NAME, VERSION], [
// Gecko based
/(navigator|netscape)\/([\w\.-]+)/i // Netscape
], [[NAME, 'Netscape'], VERSION], [
/(swiftfox)/i, // Swiftfox
/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
// IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,
// Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
/(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla
// Other
/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,
// Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir
/(links)\s\(([\w\.]+)/i, // Links
/(gobrowser)\/?([\w\.]+)*/i, // GoBrowser
/(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser
/(mosaic)[\/\s]([\w\.]+)/i // Mosaic
], [NAME, VERSION]
/* /////////////////////
// Media players BEGIN
////////////////////////
, [
/(apple(?:coremedia|))\/((\d+)[\w\._]+)/i, // Generic Apple CoreMedia
/(coremedia) v((\d+)[\w\._]+)/i
], [NAME, VERSION], [
/(aqualung|lyssna|bsplayer)\/((\d+)?[\w\.-]+)/i // Aqualung/Lyssna/BSPlayer
], [NAME, VERSION], [
/(ares|ossproxy)\s((\d+)[\w\.-]+)/i // Ares/OSSProxy
], [NAME, VERSION], [
/(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i,
// Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC
// NSPlayer/PSP-InternetRadioPlayer/Videos
/(clementine|music player daemon)\s((\d+)[\w\.-]+)/i, // Clementine/MPD
/(lg player|nexplayer)\s((\d+)[\d\.]+)/i,
/player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i // NexPlayer/LG Player
], [NAME, VERSION], [
/(nexplayer)\s((\d+)[\w\.-]+)/i // Nexplayer
], [NAME, VERSION], [
/(flrp)\/((\d+)[\w\.-]+)/i // Flip Player
], [[NAME, 'Flip Player'], VERSION], [
/(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i
// FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit
], [NAME], [
/(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i
// Gstreamer
], [NAME, VERSION], [
/(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i, // HTC Streaming Player
/(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i,
// Java/urllib/requests/wget/cURL
/(lavf)((\d+)[\d\.]+)/i // Lavf (FFMPEG)
], [NAME, VERSION], [
/(htc_one_s)\/((\d+)[\d\.]+)/i // HTC One S
], [[NAME, /_/g, ' '], VERSION], [
/(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i
// MPlayer SVN
], [NAME, VERSION], [
/(mplayer)(?:\s|\/|[unkow-]+)((\d+)[\w\.-]+)/i // MPlayer
], [NAME, VERSION], [
/(mplayer)/i, // MPlayer (no other info)
/(yourmuze)/i, // YourMuze
/(media player classic|nero showtime)/i // Media Player Classic/Nero ShowTime
], [NAME], [
/(nero (?:home|scout))\/((\d+)[\w\.-]+)/i // Nero Home/Nero Scout
], [NAME, VERSION], [
/(nokia\d+)\/((\d+)[\w\.-]+)/i // Nokia
], [NAME, VERSION], [
/\s(songbird)\/((\d+)[\w\.-]+)/i // Songbird/Philips-Songbird
], [NAME, VERSION], [
/(winamp)3 version ((\d+)[\w\.-]+)/i, // Winamp
/(winamp)\s((\d+)[\w\.-]+)/i,
/(winamp)mpeg\/((\d+)[\w\.-]+)/i
], [NAME, VERSION], [
/(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info)
// inlight radio
], [NAME], [
/(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i
// QuickTime/RealMedia/RadioApp/RadioClientApplication/
// SoundTap/Totem/Stagefright/Streamium
], [NAME, VERSION], [
/(smp)((\d+)[\d\.]+)/i // SMP
], [NAME, VERSION], [
/(vlc) media player - version ((\d+)[\w\.]+)/i, // VLC Videolan
/(vlc)\/((\d+)[\w\.-]+)/i,
/(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i, // XBMC/gvfs/Xine/XMMS/irapp
/(foobar2000)\/((\d+)[\d\.]+)/i, // Foobar2000
/(itunes)\/((\d+)[\d\.]+)/i // iTunes
], [NAME, VERSION], [
/(wmplayer)\/((\d+)[\w\.-]+)/i, // Windows Media Player
/(windows-media-player)\/((\d+)[\w\.-]+)/i
], [[NAME, /-/g, ' '], VERSION], [
/windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i
// Windows Media Server
], [VERSION, [NAME, 'Windows']], [
/(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i // RiseUP Radio Alarm
], [NAME, VERSION], [
/(rad.io)\s((\d+)[\d\.]+)/i, // Rad.io
/(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i
], [[NAME, 'rad.io'], VERSION]
//////////////////////
// Media players END
////////////////////*/
],
cpu : [[
/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i // AMD64
], [[ARCHITECTURE, 'amd64']], [
/(ia32(?=;))/i // IA32 (quicktime)
], [[ARCHITECTURE, util.lowerize]], [
/((?:i[346]|x)86)[;\)]/i // IA32
], [[ARCHITECTURE, 'ia32']], [
// PocketPC mistakenly identified as PowerPC
/windows\s(ce|mobile);\sppc;/i
], [[ARCHITECTURE, 'arm']], [
/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i // PowerPC
], [[ARCHITECTURE, /ower/, '', util.lowerize]], [
/(sun4\w)[;\)]/i // SPARC
], [[ARCHITECTURE, 'sparc']], [
/((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+;))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i
// IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
], [[ARCHITECTURE, util.lowerize]]
],
device : [[
/\((ipad|playbook);[\w\s\);-]+(rim|apple)/i // iPad/PlayBook
], [MODEL, VENDOR, [TYPE, TABLET]], [
/applecoremedia\/[\w\.]+ \((ipad)/ // iPad
], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [
/(apple\s{0,1}tv)/i // Apple TV
], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [
/(archos)\s(gamepad2?)/i, // Archos
/(hp).+(touchpad)/i, // HP TouchPad
/(hp).+(tablet)/i, // HP Tablet
/(kindle)\/([\w\.]+)/i, // Kindle
/\s(nook)[\w\s]+build\/(\w+)/i, // Nook
/(dell)\s(strea[kpr\s\d]*[\dko])/i // Dell Streak
], [VENDOR, MODEL, [TYPE, TABLET]], [
/(kf[A-z]+)\sbuild\/[\w\.]+.*silk\//i // Kindle Fire HD
], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [
/(sd|kf)[0349hijorstuw]+\sbuild\/[\w\.]+.*silk\//i // Fire Phone
], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [
/\((ip[honed|\s\w*]+);.+(apple)/i // iPod/iPhone
], [MODEL, VENDOR, [TYPE, MOBILE]], [
/\((ip[honed|\s\w*]+);/i // iPod/iPhone
], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [
/(blackberry)[\s-]?(\w+)/i, // BlackBerry
/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|huawei|meizu|motorola|polytron)[\s_-]?([\w-]+)*/i,
// BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Huawei/Meizu/Motorola/Polytron
/(hp)\s([\w\s]+\w)/i, // HP iPAQ
/(asus)-?(\w+)/i // Asus
], [VENDOR, MODEL, [TYPE, MOBILE]], [
/\(bb10;\s(\w+)/i // BlackBerry 10
], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [
// Asus Tablets
/android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone)/i
], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [
/(sony)\s(tablet\s[ps])\sbuild\//i, // Sony
/(sony)?(?:sgp.+)\sbuild\//i
], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [
/(?:sony)?(?:(?:(?:c|d)\d{4})|(?:so[-l].+))\sbuild\//i
], [[VENDOR, 'Sony'], [MODEL, 'Xperia Phone'], [TYPE, MOBILE]], [
/\s(ouya)\s/i, // Ouya
/(nintendo)\s([wids3u]+)/i // Nintendo
], [VENDOR, MODEL, [TYPE, CONSOLE]], [
/android.+;\s(shield)\sbuild/i // Nvidia
], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [
/(playstation\s[34portablevi]+)/i // Playstation
], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [
/(sprint\s(\w+))/i // Sprint Phones
], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [
/(lenovo)\s?(S(?:5000|6000)+(?:[-][\w+]))/i // Lenovo tablets
], [VENDOR, MODEL, [TYPE, TABLET]], [
/(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i, // HTC
/(zte)-(\w+)*/i, // ZTE
/(alcatel|geeksphone|huawei|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i
// Alcatel/GeeksPhone/Huawei/Lenovo/Nexian/Panasonic/Sony
], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [
/(nexus\s9)/i // HTC Nexus 9
], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [
/(nexus\s6p)/i // Huawei Nexus 6P
], [MODEL, [VENDOR, 'Huawei'], [TYPE, MOBILE]], [
/(microsoft);\s(lumia[\s\w]+)/i // Microsoft Lumia
], [VENDOR, MODEL, [TYPE, MOBILE]], [
/[\s\(;](xbox(?:\sone)?)[\s\);]/i // Microsoft Xbox
], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [
/(kin\.[onetw]{3})/i // Microsoft Kin
], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [
// Motorola
/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?)[\w\s]+build\//i,
/mot[\s-]?(\w+)*/i,
/(XT\d{3,4}) build\//i,
/(nexus\s6)/i
], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [
/android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i
], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [
/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i // HbbTV devices
], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE, SMARTTV]], [
/hbbtv.+maple;(\d+)/i
], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE, SMARTTV]], [
/\(dtv[\);].+(aquos)/i // Sharp
], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [
/android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,
/((SM-T\w+))/i
], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [ // Samsung
/smart-tv.+(samsung)/i
], [VENDOR, [TYPE, SMARTTV], MODEL], [
/((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,
/(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i,
/sec-((sgh\w+))/i
], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [
/sie-(\w+)*/i // Siemens
], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [
/(maemo|nokia).*(n900|lumia\s\d+)/i, // Nokia
/(nokia)[\s_-]?([\w-]+)*/i
], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [
/android\s3\.[\s\w;-]{10}(a\d{3})/i // Acer
], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [
/android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i // LG Tablet
], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [
/(lg) netcast\.tv/i // LG SmartTV
], [VENDOR, MODEL, [TYPE, SMARTTV]], [
/(nexus\s[45])/i, // LG
/lg[e;\s\/-]+(\w+)*/i
], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [
/android.+(ideatab[a-z0-9\-\s]+)/i // Lenovo
], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [
/linux;.+((jolla));/i // Jolla
], [VENDOR, MODEL, [TYPE, MOBILE]], [
/((pebble))app\/[\d\.]+\s/i // Pebble
], [VENDOR, MODEL, [TYPE, WEARABLE]], [
/android.+;\s(glass)\s\d/i // Google Glass
], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [
/android.+(\w+)\s+build\/hm\1/i, // Xiaomi Hongmi 'numeric' models
/android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Hongmi
/android.+(mi[\s\-_]*(?:one|one[\s_]plus|note lte)?[\s_]*(?:\d\w)?)\s+build/i // Xiaomi Mi
], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [
/android.+a000(1)\s+build/i // OnePlus
], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [
/\s(tablet)[;\/]/i, // Unidentifiable Tablet
/\s(mobile)(?:[;\/]|\ssafari)/i // Unidentifiable Mobile
], [[TYPE, util.lowerize], VENDOR, MODEL]
/*//////////////////////////
// TODO: move to string map
////////////////////////////
/(C6603)/i // Sony Xperia Z C6603
], [[MODEL, 'Xperia Z C6603'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [
/(C6903)/i // Sony Xperia Z 1
], [[MODEL, 'Xperia Z 1'], [VENDOR, 'Sony'], [TYPE, MOBILE]], [
/(SM-G900[F|H])/i // Samsung Galaxy S5
], [[MODEL, 'Galaxy S5'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
/(SM-G7102)/i // Samsung Galaxy Grand 2
], [[MODEL, 'Galaxy Grand 2'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
/(SM-G530H)/i // Samsung Galaxy Grand Prime
], [[MODEL, 'Galaxy Grand Prime'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
/(SM-G313HZ)/i // Samsung Galaxy V
], [[MODEL, 'Galaxy V'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
/(SM-T805)/i // Samsung Galaxy Tab S 10.5
], [[MODEL, 'Galaxy Tab S 10.5'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [
/(SM-G800F)/i // Samsung Galaxy S5 Mini
], [[MODEL, 'Galaxy S5 Mini'], [VENDOR, 'Samsung'], [TYPE, MOBILE]], [
/(SM-T311)/i // Samsung Galaxy Tab 3 8.0
], [[MODEL, 'Galaxy Tab 3 8.0'], [VENDOR, 'Samsung'], [TYPE, TABLET]], [
/(R1001)/i // Oppo R1001
], [MODEL, [VENDOR, 'OPPO'], [TYPE, MOBILE]], [
/(X9006)/i // Oppo Find 7a
], [[MODEL, 'Find 7a'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [
/(R2001)/i // Oppo YOYO R2001
], [[MODEL, 'Yoyo R2001'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [
/(R815)/i // Oppo Clover R815
], [[MODEL, 'Clover R815'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [
/(U707)/i // Oppo Find Way S
], [[MODEL, 'Find Way S'], [VENDOR, 'Oppo'], [TYPE, MOBILE]], [
/(T3C)/i // Advan Vandroid T3C
], [MODEL, [VENDOR, 'Advan'], [TYPE, TABLET]], [
/(ADVAN T1J\+)/i // Advan Vandroid T1J+
], [[MODEL, 'Vandroid T1J+'], [VENDOR, 'Advan'], [TYPE, TABLET]], [
/(ADVAN S4A)/i // Advan Vandroid S4A
], [[MODEL, 'Vandroid S4A'], [VENDOR, 'Advan'], [TYPE, MOBILE]], [
/(V972M)/i // ZTE V972M
], [MODEL, [VENDOR, 'ZTE'], [TYPE, MOBILE]], [
/(i-mobile)\s(IQ\s[\d\.]+)/i // i-mobile IQ
], [VENDOR, MODEL, [TYPE, MOBILE]], [
/(IQ6.3)/i // i-mobile IQ IQ 6.3
], [[MODEL, 'IQ 6.3'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [
/(i-mobile)\s(i-style\s[\d\.]+)/i // i-mobile i-STYLE
], [VENDOR, MODEL, [TYPE, MOBILE]], [
/(i-STYLE2.1)/i // i-mobile i-STYLE 2.1
], [[MODEL, 'i-STYLE 2.1'], [VENDOR, 'i-mobile'], [TYPE, MOBILE]], [
/(mobiistar touch LAI 512)/i // mobiistar touch LAI 512
], [[MODEL, 'Touch LAI 512'], [VENDOR, 'mobiistar'], [TYPE, MOBILE]], [
/////////////
// END TODO
///////////*/
],
engine : [[
/windows.+\sedge\/([\w\.]+)/i // EdgeHTML
], [VERSION, [NAME, 'EdgeHTML']], [
/(presto)\/([\w\.]+)/i, // Presto
/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links
/(icab)[\/\s]([23]\.[\d\.]+)/i // iCab
], [NAME, VERSION], [
/rv\:([\w\.]+).*(gecko)/i // Gecko
], [VERSION, NAME]
],
os : [[
// Windows based
/microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes)
], [NAME, VERSION], [
/(windows)\snt\s6\.2;\s(arm)/i, // Windows RT
/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s]+\w)*/i, // Windows Phone
/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [
// Mobile/Embedded OS
/\((bb)(10);/i // BlackBerry 10
], [[NAME, 'BlackBerry'], VERSION], [
/(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry
/(tizen)[\/\s]([\w\.]+)/i, // Tizen
/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,
// Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki
/linux;.+(sailfish);/i // Sailfish OS
], [NAME, VERSION], [
/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian
], [[NAME, 'Symbian'], VERSION], [
/\((series40);/i // Series 40
], [NAME], [
/mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS
], [[NAME, 'Firefox OS'], VERSION], [
// Console
/(nintendo|playstation)\s([wids34portablevu]+)/i, // Nintendo/Playstation
// GNU/Linux based
/(mint)[\/\s\(]?(\w+)*/i, // Mint
/(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux
/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]+)*/i,
// Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
// Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
/(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux
/(gnu)\s?([\w\.]+)*/i // GNU
], [NAME, VERSION], [
/(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS
], [[NAME, 'Chromium OS'], VERSION],[
// Solaris
/(sunos)\s?([\w\.]+\d)*/i // Solaris
], [[NAME, 'Solaris'], VERSION], [
// BSD based
/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
], [NAME, VERSION],[
/(haiku)\s(\w+)/i // Haiku
], [NAME, VERSION],[
/(ip[honead]+)(?:.*os\s([\w]+)*\slike\smac|;\sopera)/i // iOS
], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [
/(mac\sos\sx)\s?([\w\s\.]+\w)*/i,
/(macintosh|mac(?=_powerpc)\s)/i // Mac OS
], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [
// Other
/((?:open)?solaris)[\/\s-]?([\w\.]+)*/i, // Solaris
/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX
/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,
// Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS
/(unix)\s?([\w\.]+)*/i // UNIX
], [NAME, VERSION]
]
};
/////////////////
// Constructor
////////////////
var UAParser = function (uastring, extensions) {
if (!(this instanceof UAParser)) {
return new UAParser(uastring, extensions).getResult();
}
var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
var rgxmap = extensions ? util.extend(regexes, extensions) : regexes;
this.getBrowser = function () {
var browser = mapper.rgx.apply(this, rgxmap.browser);
browser.major = util.major(browser.version);
return browser;
};
this.getCPU = function () {
return mapper.rgx.apply(this, rgxmap.cpu);
};
this.getDevice = function () {
return mapper.rgx.apply(this, rgxmap.device);
};
this.getEngine = function () {
return mapper.rgx.apply(this, rgxmap.engine);
};
this.getOS = function () {
return mapper.rgx.apply(this, rgxmap.os);
};
this.getResult = function() {
return {
ua : this.getUA(),
browser : this.getBrowser(),
engine : this.getEngine(),
os : this.getOS(),
device : this.getDevice(),
cpu : this.getCPU()
};
};
this.getUA = function () {
return ua;
};
this.setUA = function (uastring) {
ua = uastring;
return this;
};
return this;
};
UAParser.VERSION = LIBVERSION;
UAParser.BROWSER = {
NAME : NAME,
MAJOR : MAJOR, // deprecated
VERSION : VERSION
};
UAParser.CPU = {
ARCHITECTURE : ARCHITECTURE
};
UAParser.DEVICE = {
MODEL : MODEL,
VENDOR : VENDOR,
TYPE : TYPE,
CONSOLE : CONSOLE,
MOBILE : MOBILE,
SMARTTV : SMARTTV,
TABLET : TABLET,
WEARABLE: WEARABLE,
EMBEDDED: EMBEDDED
};
UAParser.ENGINE = {
NAME : NAME,
VERSION : VERSION
};
UAParser.OS = {
NAME : NAME,
VERSION : VERSION
};
///////////
// Export
//////////
// check js environment
if (typeof(exports) !== UNDEF_TYPE) {
// nodejs env
if (typeof module !== UNDEF_TYPE && module.exports) {
exports = module.exports = UAParser;
}
exports.UAParser = UAParser;
} else {
// requirejs env (optional)
if (typeof(define) === FUNC_TYPE && define.amd) {
define(function () {
return UAParser;
});
} else {
// browser env
window.UAParser = UAParser;
}
}
// jQuery/Zepto specific (optional)
// Note:
// In AMD env the global scope should be kept clean, but jQuery is an exception.
// jQuery always exports to global scope, unless jQuery.noConflict(true) is used,
// and we should catch that.
var $ = window.jQuery || window.Zepto;
if (typeof $ !== UNDEF_TYPE) {
var parser = new UAParser();
$.ua = parser.getResult();
$.ua.get = function() {
return parser.getUA();
};
$.ua.set = function (uastring) {
parser.setUA(uastring);
var result = parser.getResult();
for (var prop in result) {
$.ua[prop] = result[prop];
}
};
}
})(typeof window === 'object' ? window : this);
},{}],365:[function(require,module,exports){
(function (global){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],366:[function(require,module,exports){
arguments[4][325][0].apply(exports,arguments)
},{"dup":325}],367:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],368:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":367,"_process":339,"inherits":366}],369:[function(require,module,exports){
'use strict';
// FUNCTIONS //
var isStr = Object.prototype.toString;
// IS FLOAT32ARRAY //
/**
* FUNCTION: isFloat32Array( value )
* Validates if a value is a Float32Array.
*
* @param {*} value - value to validate
* @returns {Boolean} boolean indicating if a value is a Float32Array
*/
function isFloat32Array( value ) {
return isStr.call( value ) === '[object Float32Array]';
} // end FUNCTION isFloat32Array()
// EXPORTS //
module.exports = isFloat32Array;
},{}],370:[function(require,module,exports){
(function (process,global){
'use strict'
var Transform = require('readable-stream').Transform
var duplexify = require('duplexify')
var WS = require('ws')
var Buffer = require('safe-buffer').Buffer
module.exports = WebSocketStream
function buildProxy (options, socketWrite, socketEnd) {
var proxy = new Transform({
objectMode: options.objectMode
})
proxy._destroyed = false
proxy._write = socketWrite
proxy._flush = socketEnd
proxy.destroy = function(err) {
if (this._destroyed) return
this._destroyed = true
var self = this
process.nextTick(function() {
if (err)
self.emit('error', err)
self.emit('close')
})
}
return proxy
}
function WebSocketStream(target, protocols, options) {
var stream, socket
var isBrowser = process.title === 'browser'
var isNative = !!global.WebSocket
var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
// accept the "options" Object as the 2nd argument
options = protocols
protocols = null
if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
protocols = options.protocol;
}
}
if (!options) options = {}
if (options.objectMode === undefined) {
options.objectMode = !(options.binary === true || options.binary === undefined)
}
var proxy = buildProxy(options, socketWrite, socketEnd)
if (!options.objectMode) {
proxy._writev = writev
}
// browser only: sets the maximum socket buffer size before throttling
var bufferSize = options.browserBufferSize || 1024 * 512
// browser only: how long to wait when throttling
var bufferTimeout = options.browserBufferTimeout || 1000
// use existing WebSocket object that was passed in
if (typeof target === 'object') {
socket = target
// otherwise make a new one
} else {
// special constructor treatment for native websockets in browsers, see
// https://github.com/maxogden/websocket-stream/issues/82
if (isNative && isBrowser) {
socket = new WS(target, protocols)
} else {
socket = new WS(target, protocols, options)
}
socket.binaryType = 'arraybuffer'
}
// was already open when passed in
if (socket.readyState === WS.OPEN) {
stream = proxy
} else {
stream = duplexify.obj()
socket.onopen = onopen
}
stream.socket = socket
socket.onclose = onclose
socket.onerror = onerror
socket.onmessage = onmessage
proxy.on('close', destroy)
var coerceToBuffer = !options.objectMode
function socketWriteNode(chunk, enc, next) {
// avoid errors, this never happens unless
// destroy() is called
if (socket.readyState !== WS.OPEN) {
next()
return
}
if (coerceToBuffer && typeof chunk === 'string') {
chunk = new Buffer(chunk, 'utf8')
}
socket.send(chunk, next)
}
function socketWriteBrowser(chunk, enc, next) {
if (socket.bufferedAmount > bufferSize) {
setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
return
}
if (coerceToBuffer && typeof chunk === 'string') {
chunk = new Buffer(chunk, 'utf8')
}
try {
socket.send(chunk)
} catch(err) {
return next(err)
}
next()
}
function socketEnd(done) {
socket.close()
done()
}
function onopen() {
stream.setReadable(proxy)
stream.setWritable(proxy)
stream.emit('connect')
}
function onclose() {
stream.end()
stream.destroy()
}
function onerror(err) {
stream.destroy(err)
}
function onmessage(event) {
var data = event.data
if (data instanceof ArrayBuffer) data = Buffer.from(new Uint8Array(data))
else data = Buffer.from(data, 'utf8')
proxy.push(data)
}
function destroy() {
socket.close()
}
// this is to be enabled only if objectMode is false
function writev (chunks, cb) {
var buffers = new Array(chunks.length)
for (var i = 0; i < chunks.length; i++) {
if (typeof chunks[i].chunk === 'string') {
buffers[i] = Buffer.from(chunks[i], 'utf8')
} else {
buffers[i] = chunks[i].chunk
}
}
this._write(Buffer.concat(buffers), 'binary', cb)
}
return stream
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":339,"duplexify":310,"readable-stream":350,"safe-buffer":354,"ws":371}],371:[function(require,module,exports){
var ws = null
if (typeof WebSocket !== 'undefined') {
ws = WebSocket
} else if (typeof MozWebSocket !== 'undefined') {
ws = MozWebSocket
} else {
ws = window.WebSocket || window.MozWebSocket
}
module.exports = ws
},{}],372:[function(require,module,exports){
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}
},{}],373:[function(require,module,exports){
var merge = require('merge-recursive')
var readystate = require('readystate')
var util = require('util')
var defaultOptions = require('./options')
var Constants = require('./constants')
var Events = require('./events')
var CollectLogger = require('./util/collectLogger')
var EventEmitter = require('./util/eventEmitter')
var Container = require('./wrappers/container')
var OptionsWrapper = require('./wrappers/optionsWrapper')
var Replay = require('./wrappers/visuals/replay')
var Browser = require('./util/browser')
var Resource = require('./resource')
var collectLogger, browser
function adjustOptions (options) {
var localOptions = merge.recursive(defaultOptions, options || {})
collectLogger = collectLogger || new CollectLogger(localOptions)
localOptions.logger = collectLogger
localOptions.debug = localOptions.logger.debug
OptionsWrapper.addFunctions(localOptions)
return localOptions
}
function getBrowser (localOptions) {
if (!browser) {
browser = new Browser(localOptions)
}
return browser
}
var VideomailClient = function (options) {
var localOptions = adjustOptions(options)
var container = new Container(localOptions)
var replay
EventEmitter.call(this, localOptions, 'VideomailClient')
// expose all possible events
this.events = Events
function build () {
var building = false
readystate.interactive(function () {
// it can happen that it gets called twice, i.E. when an error is thrown
// in the middle of the build() fn
if (!building && !container.isBuilt()) {
building = true
container.build()
building = false
}
})
}
this.show = function () {
if (container.isBuilt()) {
container.show()
} else {
this.once(Events.BUILT, container.show)
}
}
// automatically adds a <video> element inside the given parentElement and loads
// it with the videomail
this.replay = function (videomail, parentElement) {
function buildReplay () {
if (typeof parentElement === 'string') {
parentElement = document.getElementById(parentElement)
}
// if there is none, use the automatically generated one
if (!parentElement) {
replay = container.getReplay()
parentElement = replay.getParentElement()
} else {
replay = new Replay(parentElement, localOptions)
replay.build()
}
videomail = container.addPlayerDimensions(videomail, parentElement)
if (videomail) {
// slight delay needed to avoid HTTP 416 errors (request range unavailable)
setTimeout(function () {
replay.setVideomail(videomail)
if (container.isOutsideElementOf(parentElement)) {
// replay element must be outside of the container
container.hideForm()
} else {
container.loadForm(videomail)
}
container.showReplayOnly()
}, 150)
}
}
readystate.interactive(buildReplay)
}
this.startOver = function () {
replay && replay.hide()
container.startOver()
}
this.unload = function (e) {
readystate.removeAllListeners()
container.unload(e)
}
this.hide = function () {
container.hide()
}
this.get = function (key, cb) {
new Resource(localOptions).get(key, function (err, videomail) {
if (err) {
cb(err)
} else {
cb(null, container.addPlayerDimensions(videomail))
}
})
}
this.canRecord = function () {
return getBrowser(localOptions).canRecord()
}
// return true when a video has been recorded but is not sent yet
this.isDirty = function () {
return container.isDirty()
}
this.submit = function () {
container.submit()
}
build()
}
util.inherits(VideomailClient, EventEmitter)
Object.keys(Constants.public).forEach(function (name) {
VideomailClient[name] = Constants.public[name]
})
// just another convenient thing
VideomailClient.events = Events
module.exports = VideomailClient
},{"./constants":374,"./events":375,"./options":376,"./resource":377,"./util/browser":380,"./util/collectLogger":381,"./util/eventEmitter":382,"./wrappers/container":389,"./wrappers/optionsWrapper":392,"./wrappers/visuals/replay":401,"merge-recursive":335,"readystate":351,"util":368}],374:[function(require,module,exports){
// constants (changing these only break down functionality, so be careful)
module.exports = {
SITE_NAME_LABEL: 'x-videomail-site-name',
public: {
ENC_TYPE_APP_JSON: 'application/json',
ENC_TYPE_FORM: 'application/x-www-form-urlencoded'
}
}
},{}],375:[function(require,module,exports){
var keymirror = require('keymirror')
module.exports = keymirror({
BUILT: null, // all dom elements are ready, are in the DOM
FORM_READY: null, // form is ready, available in the DOM
LOADING_USER_MEDIA: null, // asking for webcam access
USER_MEDIA_READY: null, // user media (= webcam) is ready, loaded
CONNECTING: null, // socket is connecting to server
CONNECTED: null, // socket is connected to server
DISCONNECTED: null, // socket to server is disconnected
COUNTDOWN: null, // countdown for recording has started
RECORDING: null, // webcam is recording
STOPPING: null, // recording is being stopped (= preview)
PROGRESS: null, // start sending
BEGIN_AUDIO_ENCODING: null, // encoding video
BEGIN_VIDEO_ENCODING: null, // encoding video
RESETTING: null, // resetting everything to go back to initial state
PAUSED: null, // recording is being paused
RESUMING: null, // recording is resumed
PREVIEW: null, // video preview is set
PREVIEW_SHOWN: null, // video preview is shown
REPLAY_SHOWN: null, // submitted video is shown
INVALID: null, // form is invalid
VALIDATING: null, // form is being validated
VALID: null, // form is valid
SUBMITTING: null, // form is being submitted
SUBMITTED: null, // form has been successfully submitted
ERROR: null, // an error occured
BLOCKING: null, // something serious, most likely an error, is shown and blocks
SENDING_FIRST_FRAME: null, // emitted before the first frame is being computed
FIRST_FRAME_SENT: null, // emitted once when fist frame has been sent to server
HIDE: null, // emitted when hidden
NOTIFYING: null, // notifies user about something (not blocking)
ENABLING_AUDIO: null, // about to enable audio
DISABLING_AUDIO: null, // about to disable audio
LOADED_META_DATA: null, // raised when webcam knows its dimensions
EVENT_EMITTED: null, // for debugging only, is emitted when an event is emitted lol,
GOING_BACK: null, // going back, starting all over again,
ASKING_WEBCAM_PERMISSION: null, // when about to ask for webcam permissions
VISIBLE: null, // document just became visible
INVISIBLE: null // document just became INvisible
})
},{"keymirror":334}],376:[function(require,module,exports){
module.exports = {
logger: null, // define logging instance. leave null for default, console.
logStackSize: 30, // limits the stack size of log outputs to collect
verbose: false, // set true to log more info
baseUrl: 'https://videomail.io', // leave as it, permanent url to post videos
socketUrl: 'wss://videomail.io', // leave as it, permanent url to send frames
siteName: 'videomail-client-demo', // Required for the API. If you change it, contact me
cache: true, // reduces GET queries when loading videos
insertCss: true, // inserts predefined CSS, see examples
enablePause: true, // enable pause/resume button
enableAutoPause: true, // automatically pauses when window becomes inactive
enableSpace: true, // hitting space can pause recording
disableSubmit: false, // set this to true if you do not want to submit videos,
// but just want to record and replay these temporarily
enableAutoValidation: true, // automatically validates all form inputs if any exist and
// does not /enable disable submit button after recording
// when something else seems invalid.
enctype: 'application/json', // enctype for the form submission. currently implemented are:
// 'application/json' and 'application/x-www-form-urlencoded'
// default CSS selectors you can alter, see examples
selectors: {
containerId: 'videomail',
replayClass: 'replay',
userMediaClass: 'userMedia',
visualsClass: 'visuals',
buttonClass: null, // can also be used as a default class for all buttons
buttonsClass: 'buttons',
recordButtonClass: 'record',
pauseButtonClass: 'pause',
resumeButtonClass: 'resume',
previewButtonClass: 'preview',
recordAgainButtonClass: 'recordAgain',
submitButtonClass: 'submit',
subjectInputName: 'subject', // the form input name for subject
fromInputName: 'from', // the form input name for the from email
toInputName: 'to', // the form input name for the to email
bodyInputName: 'body', // the form input name for the message (body)
keyInputName: 'videomail_key',
parentKeyInputName: 'videomail_parent_key',
aliasInputName: 'videomail_alias',
formId: null, // automatically detects form if any
submitButtonId: null, // semi-automatically detects submit button in the form
// but if that does not work, try using the
submitButtonSelector: null // submitButtonSelector
},
audio: {
enabled: false, // set to true for experimential audio recording
'switch': false, // enables a switcher for audio recording (on/off)
volume: 0.2, // must be between 0 .. 1 but 0.20 is recommeded to avoid
// distorting at the higher volume peaks
bufferSize: 1024 // decides how often the audio is being sampled, must be a power of two.
// the higher the less traffic, but harder to adjust with rubberband
// to match with the video length on server side during encoding
},
video: {
fps: 15, // depends on your connection
limitSeconds: 30, // recording automatically stops after that limit
countdown: 3, // set it to 0 or false to disable it
// it is recommended to set one dimension only and leave the other one to auto
// because each webcam has a different aspect ratio
width: 'auto', // or use an integer for exact pixels
height: 'auto' // or use an integer for exact pixels
},
image: {
quality: 0.35,
types: ['webp', 'jpeg'] // recommended settings to make most of all browsers
},
// alter these text for internationalisation
text: {
pausedHeader: 'Paused',
pausedHint: null,
sending: 'Teleporting',
encoding: 'Encoding',
limitReached: 'Limit reached',
buttons: {
'record': 'Record video',
'recordAgain': 'Record again',
'resume': 'Resume',
'pause': 'Pause',
'preview': 'Preview'
}
},
notifier: {
entertain: false, // when true, user is entertained while waiting, see examples
entertainClass: 'bg',
entertainLimit: 6,
entertainInterval: 9000
},
timeouts: {
userMedia: 10e3, // in milliseconds, increase if you want user give more time to enable webcam
connection: 1e4, // in seconds, increase if api is slow
pingInterval: 45e3 // in milliseconds, keeps webstream (connection) alive when pausing
},
callbacks: {
// a custom callback to tweak form data before posting to server
// this is for advanced use only and shouldn't be used if possible
adjustFormDataBeforePosting: null
},
defaults: {
from: null, // define default FROM email address
to: null, // define default TO email address
subject: null, // define default subject line
body: null // define default body content
},
// show errors inside the container?
displayErrors: true,
// true = all form inputs get disabled and disappear when browser can't record
adjustFormOnBrowserError: false,
// when true, any errors will be sent to the videomail server for analysis
// ps: can be a function too returning a boolean
reportErrors: false,
// just for testing purposes to simulate browser agent handling
fakeUaString: null
}
},{}],377:[function(require,module,exports){
var superagent = require('superagent')
var Constants = require('./constants')
var CACHE_KEY = 'alias'
module.exports = function (options) {
var cache = {}
function applyDefaultValue (videomail, name) {
if (options.defaults[name] && !videomail[name]) { videomail[name] = options.defaults[name] }
return videomail
}
function applyDefaultValues (videomail) {
if (options.defaults) {
videomail = applyDefaultValue(videomail, 'from')
videomail = applyDefaultValue(videomail, 'to')
videomail = applyDefaultValue(videomail, 'subject')
videomail = applyDefaultValue(videomail, 'body')
}
return videomail
}
function packError (err, res) {
if (res && res.body && res.body.error) {
// use the server generated text instead of the superagent's default text
err = res.body.error
if (!err.message && res.text) {
err.message = res.text
}
}
return err
}
function fetch (alias, cb) {
superagent
.get('/videomail/' + alias + '/snapshot')
.set('Accept', 'application/json')
.set(Constants.SITE_NAME_LABEL, options.siteName)
.timeout(options.timeouts.connection)
.end(function (err, res) {
err = packError(err, res)
if (err) { cb(err) } else {
var videomail = res.body
if (options.cache) { cache[CACHE_KEY] = videomail }
cb(null, videomail)
}
})
}
function write (method, videomail, identifier, cb) {
if (!cb) {
cb = identifier
identifier = null
}
var queryParams = {}
var url = options.baseUrl + '/videomail/'
var request
if (identifier) {
url += identifier
}
request = superagent(method, url)
queryParams[Constants.SITE_NAME_LABEL] = options.siteName
request
.query(queryParams)
.send(videomail)
.timeout(options.timeout)
.end(function (err, res) {
err = packError(err, res)
if (err) {
cb(err)
} else {
if (options.cache && videomail[CACHE_KEY]) {
cache[videomail[CACHE_KEY]] = res.body.videomail
}
cb(null, res.body.videomail, res.body)
}
})
}
this.get = function (alias, cb) {
if (options.cache && cache[alias]) {
// keep all callbacks async
setTimeout(function () {
cb(null, cache[alias])
}, 0)
} else { fetch(alias, cb) }
}
this.reportError = function (err, cb) {
var queryParams = {}
var url = options.baseUrl + '/client-error/'
var request = superagent('post', url)
queryParams[Constants.SITE_NAME_LABEL] = options.siteName
request
.query(queryParams)
.send(err)
.timeout(options.timeout)
.end(function (err, res) {
err = packError(err, res)
if (err) {
cb && cb(err)
} else {
cb && cb()
}
})
}
this.post = function (videomail, cb) {
videomail = applyDefaultValues(videomail)
if (options.callbacks.adjustFormDataBeforePosting) {
options.callbacks.adjustFormDataBeforePosting(
videomail,
function (err, adjustedVideomail) {
if (err) {
cb(err)
} else {
write('post', adjustedVideomail, cb)
}
}
)
} else {
write('post', videomail, cb)
}
}
this.put = function (videomail, cb) {
write('put', videomail, videomail.key, cb)
}
this.form = function (formData, url, cb) {
var formType
switch (options.enctype) {
case Constants.public.ENC_TYPE_APP_JSON:
formType = 'json'
break
case Constants.public.ENC_TYPE_FORM:
formType = 'form'
break
default:
// keep all callbacks async
setTimeout(function () {
cb(new Error('Invalid enctype given: ' + options.enctype))
}, 0)
}
if (formType) {
superagent
.post(url)
.type(formType)
.send(formData)
.timeout(options.timeout)
.end(function (err, res) {
err = packError(err, res)
if (err) {
cb(err)
} else {
cb(null, res)
}
})
}
}
}
},{"./constants":374,"superagent":356}],378:[function(require,module,exports){
module.exports='@-webkit-keyframes a{0%{opacity:.9}35%{opacity:.9}50%{opacity:.1}85%{opacity:.1}to{opacity:.9}}@keyframes a{0%{opacity:.9}35%{opacity:.9}50%{opacity:.1}85%{opacity:.1}to{opacity:.9}}.IIV::-webkit-media-controls-play-button,.IIV::-webkit-media-controls-start-playback-button{opacity:0;pointer-events:none;width:5px}.videomail .visuals{position:relative}.videomail .visuals video.replay{-o-object-fit:scale-down;object-fit:scale-down}.videomail .replay,.videomail .userMedia{width:100%!important}.videomail .countdown,.videomail .pausedHeader,.videomail .pausedHint,.videomail .recordNote,.videomail .recordTimer{margin:0;height:auto}.videomail .countdown,.videomail .paused,.videomail .recordNote,.videomail .recordTimer,.videomail noscript{position:absolute}.videomail .countdown,.videomail .pausedHeader,.videomail .pausedHint,.videomail .recordNote,.videomail .recordTimer,.videomail noscript{font-weight:700}.videomail .countdown,.videomail .paused,.videomail noscript{width:100%;top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.videomail .countdown,.videomail .pausedHeader,.videomail .pausedHint{text-align:center;text-shadow:0 0 2px #fff}.videomail .countdown,.videomail .pausedHeader{opacity:.85;font-size:440%}.videomail .pausedHint{font-size:150%}.videomail .recordNote,.videomail .recordTimer{right:.7em;background:hsla(0,0%,4%,.8);padding:.4em .4em .3em;transition:all 1s ease;color:#00d814;font-family:monospace;opacity:.9}.videomail .recordNote.near,.videomail .recordTimer.near{color:#eb9369}.videomail .recordNote.nigh,.videomail .recordTimer.nigh{color:#ea4b2a}.videomail .recordTimer{top:.7em}.videomail .recordNote{top:3.6em}.videomail .recordNote:before{content:"REC";-webkit-animation:a 1s infinite;animation:a 1s infinite}.videomail .notifier{overflow:hidden;box-sizing:border-box;height:100%}.videomail .radioGroup{display:block}.videomail video{margin-bottom:0}'
},{}],379:[function(require,module,exports){
var isPOT = require('is-power-of-two')
var AudioSample = require('audio-sample')
var VideomailError = require('./videomailError')
var CHANNELS = 1
module.exports = function (userMedia, options) {
var scriptProcessor
function getAudioContext () {
// instantiate only once
if (!window.vcAudioContext) {
var AudioContext = window.AudioContext || window.webkitAudioContext
window.vcAudioContext = new AudioContext()
}
return window.vcAudioContext
}
function onAudioProcess (e, cb) {
if (!userMedia.isRecording() || userMedia.isPaused()) {
return
}
// Returns a Float32Array containing the PCM data associated with the channel,
// defined by the channel parameter (with 0 representing the first channel)
var float32Array = e.inputBuffer.getChannelData(0)
cb(new AudioSample(float32Array))
}
this.init = function (localMediaStream) {
options.debug('AudioRecorder: init()')
// creates an audio node from the microphone incoming stream
var volume = getAudioContext().createGain()
var channels = CHANNELS
var audioInput
try {
audioInput = getAudioContext().createMediaStreamSource(localMediaStream)
} catch (exc) {
var explanation = exc.toString() + 'Details: ' + JSON.stringify(getAudioContext())
throw VideomailError.create(
'Webcam has no audio',
explanation,
options
)
}
if (!isPOT(options.audio.bufferSize)) {
throw VideomailError.create('Audio buffer size must be a power of two.', options)
} else if (!options.audio.volume || options.audio.volume > 1) {
throw VideomailError.create('Audio volume must be between zero and one.', options)
}
volume.gain.value = options.audio.volume
// Create a ScriptProcessorNode with the given bufferSize and
// a single input and output channel
scriptProcessor =
getAudioContext().createScriptProcessor(
options.audio.bufferSize,
channels,
channels
)
// connect stream to our scriptProcessor
audioInput.connect(scriptProcessor)
// connect our scriptProcessor to the previous destination
scriptProcessor.connect(getAudioContext().destination)
// connect volume
audioInput.connect(volume)
volume.connect(scriptProcessor)
}
this.record = function (cb) {
options.debug('AudioRecorder: record()')
scriptProcessor.onaudioprocess = function (e) {
onAudioProcess(e, cb)
}
}
this.stop = function () {
options.debug('AudioRecorder: stop()')
if (scriptProcessor) {
scriptProcessor.onaudioprocess = undefined
}
// https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/close
getAudioContext().close().then(function () {
options.debug('AudioRecorder: audio context is closed')
delete window.vcAudioContext
})
}
this.getSampleRate = function () {
if (getAudioContext()) {
return getAudioContext().sampleRate
} else {
return -1
}
}
}
},{"./videomailError":387,"audio-sample":2,"is-power-of-two":331}],380:[function(require,module,exports){
var UAParser = require('ua-parser-js')
var defined = require('defined')
var VideomailError = require('./videomailError')
module.exports = function (options) {
options = options || {}
var firefoxDownload = 'http://www.mozilla.org/firefox/update/'
var edgeDownload = 'https://www.microsoft.com/en-us/download/details.aspx?id=48126'
var chromeDownload = 'http://www.google.com/chrome/'
var chromiumDownload = 'http://www.chromium.org/getting-involved/download-chromium'
var browseHappyLink = 'http://browsehappy.com'
var ua = defined(options.fakeUaString, (
typeof window !== 'undefined' &&
window.navigator &&
window.navigator.userAgent
), '')
var uaParser = new UAParser(ua).getResult()
var isIOS = uaParser.os.name === 'iOS'
var isChrome = uaParser.browser.name === 'Chrome'
var isChromium = uaParser.browser.name === 'Chromium'
var firefox = uaParser.browser.name === 'Firefox'
var osVersion = parseFloat(uaParser.os.version)
var isWindows = uaParser.os.name === 'Windows'
var isEdge = uaParser.browser.name === 'Edge' || (isWindows && osVersion >= 10)
var isIE = /IE/.test(uaParser.browser.name)
var isSafari = /Safari/.test(uaParser.browser.name)
var isOpera = /Opera/.test(uaParser.browser.name)
var isAndroid = /Android/.test(uaParser.os.name)
var chromeBased = isChrome || isChromium
var okBrowser = chromeBased || firefox || isAndroid || isOpera || isEdge
var self = this
var videoType
function getRecommendation () {
var warning
if (firefox) {
warning = 'Probably you need to <a href="' + firefoxDownload + '" target="_blank">' +
'upgrade Firefox</a> to fix this.'
} else if (isChrome) {
warning = 'Probably you need to <a href="' + chromeDownload + '" target="_blank">' +
'upgrade Chrome</a> to fix this.'
} else if (isChromium) {
warning = '<a href="' + chromiumDownload + '" target="_blank">' +
'Upgrade Chromium</a> to fix this.'
} else if (isIE) {
warning = 'Instead of Internet Explorer better pick' +
' <a href="' + chromeDownload + '" target="_blank">Chrome</a>,' +
' <a href="' + firefoxDownload + '" target="_blank">Firefox</a>,' +
' <a href="' + edgeDownload + '" target="_blank">Edge</a> or Android.'
} else if (isSafari) {
warning = 'Safari has no webcam support yet.<br/>Better pick' +
' <a href="' + chromeDownload + '" target="_blank">Chrome</a>,' +
' <a href="' + firefoxDownload + '" target="_blank">Firefox</a> or Android.'
}
if (options.debug) {
warning += ' Your browser is ' + JSON.stringify(uaParser.browser)
}
return warning
}
function getUserMediaWarning () {
var warning
if (isIOS) {
warning = 'On iPads/iPhones this webcam feature is missing.<br/><br/>' +
'For now, we recommend you to use a desktop computer or an Android device.'
} else {
warning = getRecommendation()
}
if (!warning) {
if (self.isChromeBased() || self.isFirefox()) {
warning = 'For the webcam feature, your browser needs an upgrade.'
} else {
warning = 'Hence we recommend you to use either ' +
'<a href="' + chromeDownload + '" target="_blank">Chrome</a>, ' +
'<a href="' + firefoxDownload + '" target="_blank">Firefox</a>, ' +
'<a href="' + edgeDownload + '" target="_blank">Edge</a> or Android.'
}
}
return warning
}
function getPlaybackWarning () {
var warning = getRecommendation()
if (!warning) {
warning = '<a href="' + browseHappyLink + '" target="_blank">Upgrading your browser</a> ' +
'might help.'
}
return warning
}
function canPlayType (video, type) {
var canPlayType
if (video && video.canPlayType) {
canPlayType = video.canPlayType('video/' + type)
}
return canPlayType
}
// just temporary
this.canRecord = function () {
var hasNavigator = typeof navigator !== 'undefined'
var canRecord = false
if (hasNavigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
canRecord = true
} else {
var getUserMediaType = hasNavigator && typeof navigator.getUserMedia_
canRecord = getUserMediaType === 'function'
}
return canRecord
}
this.checkRecordingCapabilities = function () {
var err
if (!okBrowser || !this.canRecord()) {
var classList = []
if (isIOS) {
classList.push(VideomailError.IOS_PROBLEM)
} else {
classList.push(VideomailError.BROWSER_PROBLEM)
}
err = VideomailError.create({
message: 'Sorry, your browser is unable to use webcams'
}, getUserMediaWarning(), options, {
classList: classList
})
}
return err
}
this.checkPlaybackCapabilities = function (video) {
var err, message
if (!video) {
message = 'No HTML5 support for video tag!'
} else if (!this.getVideoType(video)) {
message = 'Your old browser cannot support modern video codecs'
} else if (!video.setAttribute) {
// fixes "Not implemented" error on older browsers
message = 'Unable to set video attributes in your old browser'
}
if (message) {
err = VideomailError.create(message, getPlaybackWarning(), options)
}
return err
}
this.checkBufferTypes = function () {
var err
if (typeof window === 'undefined' || typeof window.atob === 'undefined') {
err = VideomailError.create('atob is not supported', options)
} else if (typeof window.ArrayBuffer === 'undefined') {
err = VideomailError.create('ArrayBuffers are not supported', options)
} else if (typeof window.Uint8Array === 'undefined') {
err = VideomailError.create('Uint8Arrays are not supported', options)
}
return err
}
this.getVideoType = function (video) {
if (!videoType) {
// there is a bug in canPlayType within chrome for mp4
if (canPlayType(video, 'mp4') && !chromeBased) {
videoType = 'mp4'
} else if (canPlayType(video, 'webm')) {
videoType = 'webm'
}
}
return videoType
}
this.getNoAccessIssue = function () {
var message = 'Unable to access webcam'
var explanation
if (this.isChromeBased()) {
explanation = 'Click on the allow button to grant access to your webcam.'
} else if (this.isFirefox()) {
explanation = 'Please grant Firefox access to your webcam.'
} else {
explanation = 'Your system does not let your browser access your webcam.'
}
return VideomailError.create(message, explanation, options)
}
this.isChromeBased = function () {
return chromeBased
}
this.isFirefox = function () {
return firefox
}
this.isEdge = function () {
return isEdge
}
this.getUsefulData = function () {
return {
browser: uaParser.browser,
device: uaParser.device,
os: uaParser.os,
engine: uaParser.engine,
userAgent: ua
}
}
}
},{"./videomailError":387,"defined":306,"ua-parser-js":364}],381:[function(require,module,exports){
var util = require('util')
var Browser = require('./browser')
module.exports = function (localOptions) {
localOptions = localOptions || {}
var browser = new Browser(localOptions)
var logger = localOptions.logger || console
var containerId = (localOptions.selectors && localOptions.selectors.containerId) || 'undefined container id'
var stack = []
function lifo (level, parameters) {
var line = util.format.apply(util, parameters)
if (stack.length > localOptions.logStackSize) {
stack.pop()
}
stack.push('[' + level + '] ' + line)
return line
}
function addContainerId (firstArgument) {
return '#' + containerId + ' [' + new Date().toLocaleTimeString() + '] > ' + firstArgument
}
// workaround: since we cannot overwrite console.log without having the correct file and line number
// we'll use groupCollapsed() and trace() instead to get these.
this.debug = function () {
// always add it for better client error reports
var args = [].slice.call(arguments, 0)
args[0] = addContainerId(args[0])
var output = lifo('debug', args)
if (localOptions.verbose) {
if (browser.isFirefox()) {
logger.debug(output)
} else if (logger.groupCollapsed) {
logger.groupCollapsed(output)
logger.trace('Trace')
logger.groupEnd()
} else if (logger.debug) {
logger.debug(output)
} else {
// last resort if everything else fails for any weird reasons
console.log(output)
}
}
}
this.error = function () {
var args = [].slice.call(arguments, 0)
args[0] = addContainerId(args[0])
logger.error(lifo('error', args))
}
this.warn = function () {
var args = [].slice.call(arguments, 0)
args[0] = addContainerId(args[0])
logger.warn(lifo('warn', args))
}
this.getLines = function () {
return stack
}
}
},{"./browser":380,"util":368}],382:[function(require,module,exports){
var despot = require('despot')
var VideomailError = require('./videomailError')
var Events = require('./../events')
// TODO: MAKE EVENT EMITTING IN DESPOT NOT GLOBAL BUT BY CONTAINER ID INSTEAD
module.exports = function (options, name) {
this.emit = function (event) {
var args = Array.prototype.slice.call(arguments, 0)
if (!event) {
throw VideomailError.create('You cannot emit without an event.', options)
}
// Automatically convert errors to videomail errors
if (event === Events.ERROR) {
var err = args[1]
err = VideomailError.create(err, options)
args[1] = err
}
if (options.debug) {
if (event !== 'removeListener' && event !== 'newListener') {
var moreArguments
if (args[1]) {
moreArguments = args.slice(1)
}
if (moreArguments) {
options.debug('%s emits: %s', name, event, moreArguments)
} else {
options.debug('%s emits: %s', name, event)
}
}
}
var result = despot.emit.apply(despot, args)
// Todo: have this emitted through a configuration because it is pretty noisy
// if (event !== Events.EVENT_EMITTED)
// this.emit(Events.EVENT_EMITTED, event)
return result
}
this.on = function (eventName, cb) {
return despot.on(eventName, cb)
}
this.once = function (eventName, cb) {
return despot.once(eventName, cb)
}
this.listeners = function (eventName) {
return despot.listeners(eventName)
}
this.removeListener = function (eventName, cb) {
return despot.removeListener(eventName, cb)
}
this.removeAllListeners = function () {
despot.removeAllListeners()
}
}
},{"./../events":375,"./videomailError":387,"despot":307}],383:[function(require,module,exports){
var filesize = require('filesize')
var humanizeDuration = require('humanize-duration')
module.exports = {
filesize: function (bytes, round) {
return filesize(bytes, {
round: round
})
},
toTime: function (t) {
return humanizeDuration(t)
}
}
},{"filesize":315,"humanize-duration":321}],384:[function(require,module,exports){
// taken from
// https://bbc.github.io/tal/jsdoc/events_mediaevent.js.html
module.exports = [
// The user agent begins looking for media data, as part of
// the resource selection algorithm.
'loadstart',
// The user agent is intentionally not currently fetching media data,
// but does not have the entire media resource downloaded. networkState equals NETWORK_IDLE
'suspend',
// Playback has begun. Fired after the play() method has returned,
// or when the autoplay attribute has caused playback to begin.
// paused is newly false.
// 'play', commented out since it has special treatment
// The user agent has just determined the duration and dimensions of the
// media resource and the timed tracks are ready.
// readyState is newly equal to HAVE_METADATA or greater for the first time.
// 'loadedmetadata', commented out since it has special treatment
// The user agent is fetching media data.
'progress',
// The user agent is intentionally not currently fetching media data,
// but does not have the entire media resource downloaded.
// 'suspend', // commented out, we are already listening to it in code
// Event The user agent stops fetching the media data before it is completely downloaded,
// but not due to an error. error is an object with the code MEDIA_ERR_ABORTED.
'abort',
// A media element whose networkState was previously not in the NETWORK_EMPTY
// state has just switched to that state (either because of a fatal error
// during load that's about to be reported, or because the load() method was
// invoked while the resource selection algorithm was already running).
'emptied',
// The user agent is trying to fetch media data, but data is
// unexpectedly not forthcoming
'stalled',
// Playback has been paused. Fired after the pause() method has returned.
// paused is newly true.
'pause',
// The user agent can render the media data at the current playback position
// for the first time.
// readyState newly increased to HAVE_CURRENT_DATA or greater for the first time.
'loadeddata',
// Playback has stopped because the next frame is not available, but the user
// agent expects that frame to become available in due course.
// readyState is newly equal to or less than HAVE_CURRENT_DATA,
// and paused is false. Either seeking is true, or the current playback
// position is not contained in any of the ranges in buffered.
// It is possible for playback to stop for two other reasons without
// paused being false, but those two reasons do not fire this event:
// maybe playback ended, or playback stopped due to errors.
'waiting',
// Playback has started. readyState is newly equal to or greater than
// HAVE_FUTURE_DATA, paused is false, seeking is false,
// or the current playback position is contained in one of the ranges in buffered.
'playing',
// The user agent can resume playback of the media data,
// but estimates that if playback were to be started now, the media resource
// could not be rendered at the current playback rate up to its end without
// having to stop for further buffering of content.
// readyState newly increased to HAVE_FUTURE_DATA or greater.
'canplay',
// The user agent estimates that if playback were to be started now,
// the media resource could be rendered at the current playback rate
// all the way to its end without having to stop for further buffering.
// readyState is newly equal to HAVE_ENOUGH_DATA.
'canplaythrough',
// The seeking IDL attribute changed to true and the seek operation is
// taking long enough that the user agent has time to fire the event.
'seeking',
// The seeking IDL attribute changed to false.
'seeked',
// Playback has stopped because the end of the media resource was reached.
// currentTime equals the end of the media resource; ended is true.
'ended',
// Either the defaultPlaybackRate or the playbackRate attribute
// has just been updated.
'ratechange',
// The duration attribute has just been updated.
'durationchange',
// Either the volume attribute or the muted attribute has changed.
// Fired after the relevant attribute's setter has returned.
'volumechange'
// commented out, happen too often
// The current playback position changed as part of normal playback or in
// an especially interesting way, for example discontinuously.
// 'timeupdate'
]
},{}],385:[function(require,module,exports){
var DASH = '- '
var SEPARATOR = '<br/>' + DASH
function arrayToString (array) {
if (array.length > 0) {
var lines = []
array.forEach(function (element) {
if (element && element.toString) {
lines.push(element.toString())
}
})
return DASH + lines.join(SEPARATOR)
}
}
function objectToString (object, options) {
var propertyNames = Object.getOwnPropertyNames(object)
var excludes = (options && options.excludes) || null
var lines = []
var sLines
if (propertyNames.length > 0) {
var exclude = false
propertyNames.forEach(function (name) {
if (excludes) {
exclude = excludes.indexOf(name) >= 0
}
if (!exclude && object[name] && object[name].toString) {
lines.push(object[name].toString())
}
})
}
if (lines.length === 1) {
sLines = lines.join()
} else if (lines.length > 1) {
sLines = DASH + lines.join(SEPARATOR)
}
return sLines
}
module.exports = function (anything, options) {
if (anything === null) {
return 'null'
} else if (typeof anything === 'undefined') {
return 'undefined'
} else if (typeof anything === 'string') {
return anything
} else if (Array.isArray(anything)) {
return arrayToString(anything)
} else if (typeof anything === 'object') {
return objectToString(anything, options)
} else {
return anything.toString()
}
}
},{}],386:[function(require,module,exports){
require('core-js/shim')
require('classlist.js')
require('element-closest') // needed for IE 11
module.exports = function (window, navigator) {
// https://github.com/julienetie/request-frame/issues/6
window.screen = window.screen || {}
// https://github.com/julienetie/request-frame
require('request-frame')('native')
// avoids warning "navigator.mozGetUserMedia has been replaced by navigator.mediaDevices.getUserMedia",
// see https://github.com/binarykitchen/videomail-client/issues/79
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// do not shim
} else {
navigator.getUserMedia_ =
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
}
window.AudioContext = window.AudioContext || window.webkitAudioContext
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL
var methods = [
'debug', 'groupCollapsed', 'groupEnd', 'error',
'exception', 'info', 'log', 'trace', 'warn'
]
var noop = function () {}
var console = (window.console = window.console || {})
var method
var length = methods.length
while (length--) {
method = methods[length]
if (!console[method]) console[method] = noop
}
}
},{"classlist.js":10,"core-js/shim":303,"element-closest":313,"request-frame":353}],387:[function(require,module,exports){
// https://github.com/tgriesser/create-error
var createError = require('create-error')
var originalPretty = require('./pretty')
var Resource = require('./../resource')
var VIDEOMAIL_ERR_NAME = 'Videomail Error'
var VideomailError = createError(Error, VIDEOMAIL_ERR_NAME, {
'explanation': undefined,
'logLines': undefined,
'useragent': undefined,
'url': undefined,
'stack': undefined
})
// shim pretty to exclude stack always
var pretty = function (anything) {
return originalPretty(anything, {excludes: ['stack']})
}
// static and public attribute of this class
VideomailError.PERMISSION_DENIED = 'PERMISSION_DENIED'
VideomailError.NOT_ALLOWED_ERROR = 'NotAllowedError'
VideomailError.NOT_CONNECTED = 'Not connected'
VideomailError.DOM_EXCEPTION = 'DOMException'
VideomailError.STARTING_FAILED = 'Starting video failed'
VideomailError.MEDIA_DEVICE_NOT_SUPPORTED = 'MediaDeviceNotSupported'
VideomailError.BROWSER_PROBLEM = 'browser-problem'
VideomailError.WEBCAM_PROBLEM = 'webcam-problem'
VideomailError.IOS_PROBLEM = 'ios-problem'
// static function to convert an error into a videomail error
VideomailError.create = function (err, explanation, options, parameters) {
if (err && err.name === VIDEOMAIL_ERR_NAME) {
return err
}
if (!options && explanation) {
options = explanation
explanation = undefined
}
options = options || {}
parameters = parameters || {}
var classList = parameters.classList || []
// Require Browser here, not at the top of the file to avoid
// recursion. Because the Browser class is requiring this file as well.
var Browser = require('./browser')
var browser = new Browser(options)
var errType
var message
var stack
// whole code is ugly because all browsers behave so differently :(
if (typeof err === 'object') {
if (err.code === 1 && err.PERMISSION_DENIED === 1) {
errType = VideomailError.PERMISSION_DENIED
} else if (err.constructor && err.constructor.name === VideomailError.DOM_EXCEPTION) {
errType = VideomailError.DOM_EXCEPTION
} else if (err.message === VideomailError.STARTING_FAILED) {
errType = err.message
} else if (err.name) {
errType = err.name
} else if (err.type === 'error' && err.target.bufferedAmount === 0) {
errType = VideomailError.NOT_CONNECTED
}
} else if (err === VideomailError.NOT_CONNECTED) {
errType = VideomailError.NOT_CONNECTED
} else {
errType = err
}
if (err && err.stack) {
stack = err.stack
}
switch (errType) {
case 'NotFoundError':
case 'NO_DEVICES_FOUND':
message = 'No webcam found'
explanation = 'Your browser cannot find a webcam attached to your machine.'
classList.push(VideomailError.WEBCAM_PROBLEM)
break
case 'PermissionDismissedError':
message = 'Ooops, you didn\'t give me any permissions?'
explanation = 'Looks like you skipped the webcam permission dialogue.<br/>' +
'Please grant access next time the dialogue appears.'
classList.push(VideomailError.WEBCAM_PROBLEM)
break
case VideomailError.NOT_ALLOWED_ERROR:
case VideomailError.PERMISSION_DENIED:
case 'PermissionDeniedError':
message = 'Permission denied'
if (browser.isChromeBased() || browser.isFirefox() || browser.isEdge()) {
explanation = 'Permission to access your webcam has been denied. ' +
'This can have two reasons:<br/>' +
'a) you blocked access to webcam; or<br/>' +
'b) your webcam is already in use.'
} else {
explanation = 'Permission to access your webcam has been denied.'
}
classList.push(VideomailError.WEBCAM_PROBLEM)
break
case 'HARDWARE_UNAVAILABLE':
message = 'Webcam is unavailable'
explanation = 'Maybe it is already busy in another window?'
if (browser.isChromeBased()) {
explanation += ' Or you have to allow access above?'
}
classList.push(VideomailError.WEBCAM_PROBLEM)
break
case VideomailError.NOT_CONNECTED:
message = 'Unable to transfer data'
explanation = 'Unable to maintain a websocket to the server. Either server or ' +
'your connection is down. Trying to reconnect every two seconds …'
break
case 'NO_VIDEO_FEED':
message = 'No video feed found!'
explanation = 'Your webcam is already used in another browser.'
classList.push(VideomailError.WEBCAM_PROBLEM)
break
case VideomailError.STARTING_FAILED:
message = 'Starting video failed'
explanation = 'Most likely this happens when the webam is already active in another browser.'
classList.push(VideomailError.WEBCAM_PROBLEM)
break
case 'DevicesNotFoundError':
message = 'No available webcam could be found'
explanation = 'Looks like you do not have any webcam attached to your machine; or ' +
'the one you plugged in is already used.'
classList.push(VideomailError.WEBCAM_PROBLEM)
break
case VideomailError.DOM_EXCEPTION:
if (err.code === 9) {
var newUrl = 'https:' + window.location.href.substring(window.location.protocol.length)
message = 'Security upgrade neded'
explanation = 'Click <a href="' + newUrl + '">here</a> to switch to HTTPs which is more safe ' +
' and enables encrypted videomail transfers.'
classList.push(VideomailError.BROWSER_PROBLEM)
} else {
message = VideomailError.DOM_EXCEPTION
explanation = pretty(err)
}
break
// Chrome has a weird problem where if you try to do a getUserMedia request too early, it
// can return a MediaDeviceNotSupported error (even though nothing is wrong and permission
// has been granted). Look at userMediaErrorCallback() in recorder, there we do not
// emit those kind of errors further and just retry.
//
// but for whatever reasons, if it happens to reach this code, then investigate this further.
case VideomailError.MEDIA_DEVICE_NOT_SUPPORTED:
message = 'Media device not supported'
explanation = pretty(err)
break
default:
var originalExplanation = explanation
if (explanation && typeof explanation === 'object') {
explanation = pretty(explanation)
}
// it can be that explanation itself is an error object
// error objects can be prettified to undefined sometimes
if (!explanation && originalExplanation) {
if (originalExplanation.message) {
explanation = originalExplanation.message
} else {
// tried toString before but nah
explanation = JSON.stringify(originalExplanation)
}
}
if (err && typeof err === 'string') {
message = err
} else {
if (err) {
if (err.message) {
message = pretty(err.message)
}
}
if (err && err.explanation) {
if (!explanation) {
explanation = pretty(err.explanation)
} else {
explanation += ';<br/>' + pretty(err.explanation)
}
}
if (err && err.details) {
var details = pretty(err.details)
if (!explanation) {
explanation = details
} else {
explanation += ';<br/>' + details
}
}
}
// for weird, undefined cases
if (!message) {
if (errType) {
message = errType
}
if (!explanation && err) {
explanation = pretty(err, {excludes: ['stack']})
}
// avoid dupes
if (pretty(message) === explanation) {
explanation = undefined
}
}
break
}
var logLines = null
if (options.logger && options.logger.getLines) {
logLines = options.logger.getLines()
}
if (stack) {
message = new Error(message)
message.stack = stack
}
var errCode = 'none'
if (err) {
errCode = 'code=' + (err.code ? err.code : 'undefined')
errCode += ', type=' + (err.type ? err.type : 'undefined')
errCode += ', name=' + (err.name ? err.name : 'undefined')
}
var videomailError = new VideomailError(message, {
explanation: explanation,
logLines: logLines,
client: browser.getUsefulData(),
url: window.location.href,
code: errCode,
stack: stack // have to assign it manually again because it is kinda protected
})
var resource
var reportErrors = false
if (options.reportErrors) {
if (typeof options.reportErrors === 'function') {
reportErrors = options.reportErrors(videomailError)
} else {
reportErrors = options.reportErrors
}
}
if (reportErrors) {
resource = new Resource(options)
}
if (resource) {
resource.reportError(videomailError, function (err2) {
if (err2) {
console.error('Unable to report error', err2)
}
})
}
function hasClass (name) {
return classList.indexOf(name) >= 0
}
function isBrowserProblem () {
return hasClass(VideomailError.BROWSER_PROBLEM) ||
parameters.browserProblem
}
// add some public functions
// this one is useful so that the notifier can have different css classes
videomailError.getClassList = function () {
return classList
}
videomailError.removeDimensions = function () {
return hasClass(VideomailError.IOS_PROBLEM)
}
videomailError.hideButtons = function () {
return isBrowserProblem() || hasClass(VideomailError.IOS_PROBLEM)
}
videomailError.hideForm = function () {
return hasClass(VideomailError.IOS_PROBLEM)
}
return videomailError
}
module.exports = VideomailError
},{"./../resource":377,"./browser":380,"./pretty":385,"create-error":305}],388:[function(require,module,exports){
var util = require('util')
var h = require('hyperscript')
var hidden = require('hidden')
var contains = require('contains')
var Events = require('./../events')
var EventEmitter = require('./../util/eventEmitter')
var Buttons = function (container, options) {
EventEmitter.call(this, options, 'Buttons')
var self = this
var buttonsElement,
recordButton,
pauseButton,
resumeButton,
previewButton,
recordAgainButton,
submitButton,
audioOnRadioPair,
audioOffRadioPair,
built
function hide (elements) {
if (elements && !Array.isArray(elements)) {
elements = [elements]
}
elements && elements.forEach(function (element) {
hidden(element, true)
})
}
function show (elements) {
if (elements && !Array.isArray(elements)) {
elements = [elements]
}
elements && elements.forEach(function (element) {
hidden(element, false)
})
}
function isShown (elements) {
var isShown = elements && true
if (elements && !Array.isArray(elements)) {
elements = [elements]
}
elements && elements.forEach(function (element) {
isShown = isShown && element && !hidden(element)
})
return isShown
}
function disable (elements) {
if (elements && !Array.isArray(elements)) {
elements = [elements]
}
elements && elements.forEach(function (element) {
if (element.tagName === 'INPUT' || element.tagName === 'BUTTON') {
element.disabled = true
} else {
element.classList.add('disabled')
}
})
}
function enable (elements) {
if (elements && !Array.isArray(elements)) {
elements = [elements]
}
elements && elements.forEach(function (element) {
if (element.tagName === 'INPUT' || element.tagName === 'BUTTON') {
element.disabled = false
} else {
element.classList.remove('disabled')
}
})
}
function adjustButton (buttonElement, show, type) {
disable(buttonElement)
if (type) {
buttonElement.type = type
} else if (!buttonElement.type) {
buttonElement.type = 'button'
}
!show && hide(buttonElement)
return buttonElement
}
function replaceClickHandler (element, clickHandler) {
var wrappedClickHandler = function (e) {
e && e.preventDefault()
try {
clickHandler({event: e})
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
element.onclick = wrappedClickHandler
}
function makeRadioButtonPair (options) {
var radioButtonElement,
radioButtonGroup
if (options.id) {
radioButtonElement = document.getElementById(options.id)
}
if (!radioButtonElement) {
radioButtonElement = h('input#' + options.id, {
type: 'radio',
name: options.name,
value: options.value,
checked: options.checked
})
radioButtonGroup = h('span.radioGroup', radioButtonElement, h('label', {
'htmlFor': options.id
}, options.label))
// double check that submit button is already in the buttonsElement container as a child?
if (submitButton && contains(buttonsElement, submitButton)) {
buttonsElement.insertBefore(radioButtonGroup, submitButton)
} else {
buttonsElement.appendChild(radioButtonGroup)
}
}
if (options.changeHandler) {
radioButtonElement.onchange = options.changeHandler
}
disable(radioButtonElement)
return [radioButtonElement, radioButtonGroup]
}
function makeButton (buttonClass, text, clickHandler, show, id, type, selector) {
var buttonElement
if (id) {
buttonElement = document.getElementById(id)
} else if (selector) {
buttonElement = document.querySelector(selector)
} else {
buttonElement = buttonsElement.querySelector('.' + buttonClass)
}
if (!buttonElement) {
if (options.selectors.buttonClass) {
buttonClass += '.' + options.selectors.buttonClass
}
buttonElement = h('button.' + buttonClass)
buttonElement = adjustButton(buttonElement, show, type)
buttonElement.innerHTML = text
// double check that submit button is already in the buttonsElement container
if (submitButton && contains(buttonsElement, submitButton)) {
buttonsElement.insertBefore(buttonElement, submitButton)
} else {
buttonsElement.appendChild(buttonElement)
}
} else {
buttonElement = adjustButton(buttonElement, show)
}
if (clickHandler) {
replaceClickHandler(buttonElement, clickHandler)
}
return buttonElement
}
function buildButtons () {
if (!options.disableSubmit) {
if (!submitButton) {
submitButton = makeButton(
options.selectors.submitButtonClass,
'Submit',
null,
true,
options.selectors.submitButtonId,
'submit',
options.selectors.submitButtonSelector
)
} else {
disable(submitButton)
}
// no need to listen to the submit event when it's already listened
// within the form element class
if (!container.hasForm() && submitButton) {
replaceClickHandler(submitButton, submit)
}
}
recordButton = makeButton(
options.selectors.recordButtonClass,
options.text.buttons.record,
record,
false
)
if (options.enablePause) {
pauseButton = makeButton(
options.selectors.pauseButtonClass,
options.text.buttons.pause,
container.pause,
false
)
}
if (options.enablePause) {
resumeButton = makeButton(
options.selectors.resumeButtonClass,
options.text.buttons.resume,
container.resume,
false
)
}
// show stop only when pause is enabled - looks better that way otherwise button
// move left and right between record and stop (preview)
previewButton = makeButton(
options.selectors.previewButtonClass,
options.text.buttons.preview,
container.stop,
false
)
recordAgainButton = makeButton(
options.selectors.recordAgainButtonClass,
options.text.buttons.recordAgain,
recordAgain,
false
)
if (options.audio && options.audio.switch) {
audioOffRadioPair = makeRadioButtonPair({
id: 'audioOffOption',
name: 'audio',
value: 'off',
label: 'Audio Off',
checked: !options.isAudioEnabled(),
changeHandler: function () {
container.disableAudio()
}
})
audioOnRadioPair = makeRadioButtonPair({
id: 'audioOnOption',
name: 'audio',
value: 'on',
label: 'Audio On (Beta)',
checked: options.isAudioEnabled(),
changeHandler: function () {
container.enableAudio()
}
})
}
}
function onFormReady (options) {
// no need to show record button when doing a record again
if (!isShown(recordAgainButton)) {
if (!options.paused) { show(recordButton) }
}
if (!options.paused) {
disable(previewButton)
hide(previewButton)
}
}
function onGoingBack () {
hide(recordAgainButton)
show(recordButton)
}
function onReplayShown () {
self.hide()
}
function onUserMediaReady (options) {
onFormReady(options)
if (isShown(recordButton)) {
enable(recordButton)
}
if (isShown(audioOnRadioPair)) {
enable(audioOnRadioPair)
}
if (isShown(audioOffRadioPair)) {
enable(audioOffRadioPair)
}
disable(submitButton)
}
function onResetting () {
disable(submitButton)
self.reset()
}
function onPreview () {
hide(recordButton)
hide(previewButton)
disable(audioOnRadioPair)
disable(audioOffRadioPair)
show(recordAgainButton)
enable(recordAgainButton)
if (!options.enableAutoValidation) {
enable(submitButton)
}
}
this.enableSubmit = function () {
enable(submitButton)
}
this.adjustButtonsForPause = function () {
if (!self.isCountingDown()) {
pauseButton && hide(pauseButton)
show(resumeButton)
enable(resumeButton)
hide(recordButton)
show(previewButton)
enable(previewButton)
}
}
function onFirstFrameSent () {
hide(recordButton)
hide(recordAgainButton)
if (pauseButton) {
show(pauseButton)
enable(pauseButton)
}
enable(previewButton)
show(previewButton)
}
function onRecording (framesCount) {
// it is possible to hide while recording, hence
// check framesCount first (coming from recorder)
if (framesCount > 1) { onFirstFrameSent() } else {
disable(audioOffRadioPair)
disable(audioOnRadioPair)
disable(recordAgainButton)
disable(recordButton)
}
}
function onResuming () {
hide(resumeButton)
hide(recordButton)
if (pauseButton) {
enable(pauseButton)
show(pauseButton)
}
}
function onStopping () {
disable(previewButton)
hide(pauseButton)
hide(resumeButton)
}
function onCountdown () {
disable(recordButton)
disable(audioOffRadioPair)
disable(audioOnRadioPair)
}
function onSubmitting () {
disable(submitButton)
disable(recordAgainButton)
}
function onSubmitted () {
disable(previewButton)
disable(recordAgainButton)
disable(recordButton)
disable(submitButton)
}
function onInvalid () {
if (options.enableAutoValidation) {
disable(submitButton)
}
}
function onValid () {
if (options.enableAutoValidation) {
enable(submitButton)
}
}
function onHidden () {
hide(recordButton)
hide(previewButton)
hide(recordAgainButton)
hide(resumeButton)
}
function onEnablingAudio () {
disable(recordButton)
disable(audioOnRadioPair)
disable(audioOffRadioPair)
}
function onDisablingAudio () {
disable(recordButton)
disable(audioOnRadioPair)
disable(audioOffRadioPair)
}
function recordAgain () {
disable(recordAgainButton)
container.beginWaiting()
container.recordAgain()
}
function submit () {
container.submit()
}
function record (params) {
disable(recordButton)
container.record(params)
}
function initEvents () {
self.on(Events.USER_MEDIA_READY, function (options) {
onUserMediaReady(options)
}).on(Events.PREVIEW, function () {
onPreview()
}).on(Events.PAUSED, function () {
self.adjustButtonsForPause()
}).on(Events.RECORDING, function (framesCount) {
onRecording(framesCount)
}).on(Events.FIRST_FRAME_SENT, function () {
onFirstFrameSent()
}).on(Events.RESUMING, function () {
onResuming()
}).on(Events.STOPPING, function () {
onStopping()
}).on(Events.COUNTDOWN, function () {
onCountdown()
}).on(Events.SUBMITTING, function () {
onSubmitting()
}).on(Events.RESETTING, function () {
onResetting()
}).on(Events.INVALID, function () {
onInvalid()
}).on(Events.VALID, function () {
onValid()
}).on(Events.SUBMITTED, function () {
onSubmitted()
}).on(Events.HIDE, function () {
onHidden()
}).on(Events.FORM_READY, function (options) {
onFormReady(options)
}).on(Events.REPLAY_SHOWN, function () {
onReplayShown()
}).on(Events.GOING_BACK, function () {
onGoingBack()
}).on(Events.ENABLING_AUDIO, function () {
onEnablingAudio()
}).on(Events.DISABLING_AUDIO, function () {
onDisablingAudio()
}).on(Events.ERROR, function (err) {
// since https://github.com/binarykitchen/videomail-client/issues/60
// we hide areas to make it easier for the user
if (err.hideButtons && err.hideButtons() && options.adjustFormOnBrowserError) {
self.hide()
}
})
}
this.reset = function () {
options.debug('Buttons: reset()')
disable(pauseButton)
disable(resumeButton)
disable(recordButton)
disable(previewButton)
disable(recordAgainButton)
}
this.isRecordAgainButtonEnabled = function () {
return !recordAgainButton.disabled
}
this.isRecordButtonEnabled = function () {
return !recordButton.disabled
}
this.setSubmitButton = function (newSubmitButton) {
submitButton = newSubmitButton
}
this.getSubmitButton = function () {
return submitButton
}
this.build = function () {
buttonsElement = container.querySelector('.' + options.selectors.buttonsClass)
if (!buttonsElement) {
buttonsElement = h('div.' + options.selectors.buttonsClass)
container.appendChild(buttonsElement)
}
buildButtons()
!built && initEvents()
built = true
}
this.unload = function () {
built = false
}
this.hide = function () {
hide(buttonsElement)
}
this.show = function () {
show(buttonsElement)
}
this.isCountingDown = function () {
return container.isCountingDown()
}
}
util.inherits(Buttons, EventEmitter)
module.exports = Buttons
},{"./../events":375,"./../util/eventEmitter":382,"contains":12,"hidden":320,"hyperscript":322,"util":368}],389:[function(require,module,exports){
var insertCss = require('insert-css')
var merge = require('merge-recursive')
var hidden = require('hidden')
var util = require('util')
var Visibility = require('document-visibility')
var Dimension = require('./dimension')
var Visuals = require('./visuals')
var Buttons = require('./buttons')
var Form = require('./form')
var Resource = require('./../resource')
var Events = require('./../events')
var EventEmitter = require('./../util/eventEmitter')
var VideomailError = require('./../util/videomailError')
var css = require('./../styles/css/main.min.css.js')
var Container = function (options) {
EventEmitter.call(this, options, 'Container')
var self = this
var visibility = Visibility()
var visuals = new Visuals(this, options)
var buttons = new Buttons(this, options)
var resource = new Resource(options)
var htmlElement = document && document.querySelector && document.querySelector('html')
var debug = options.debug
var hasError = false
var submitted = false
var lastValidation = false
var containerElement
var built
var form
function prependDefaultCss () {
insertCss(css, {prepend: true})
}
// since https://github.com/binarykitchen/videomail-client/issues/87
function findParentFormElement () {
return containerElement.closest('form')
}
function getFormElement () {
var formElement
if (containerElement.tagName === 'FORM') {
formElement = containerElement
} else if (options.selectors.formId) {
formElement = document.getElementById(options.selectors.formId)
} else {
formElement = findParentFormElement()
}
return formElement
}
function buildForm () {
var formElement = getFormElement()
if (formElement) {
form = new Form(self, formElement, options)
var submitButton = form.findSubmitButton()
submitButton && buttons.setSubmitButton(submitButton)
form.build()
}
}
function buildChildren () {
if (!containerElement.classList) {
self.emit(Events.ERROR, VideomailError.create('Sorry, your browser is too old!'))
} else {
containerElement.classList.add('videomail')
buttons.build()
visuals.build()
}
}
function processError (err) {
hasError = true
if (err.stack) {
options.logger.error(err.stack)
} else {
options.logger.error(err)
}
if (options.displayErrors) {
visuals.error(err)
} else {
visuals.reset()
}
}
function initEvents () {
window.addEventListener('beforeunload', function (e) {
self.unload(e)
})
visibility.onChange(function (visible) {
// built? see https://github.com/binarykitchen/videomail.io/issues/326
if (built) {
if (visible) {
if (options.isAutoPauseEnabled() && self.isCountingDown()) {
self.resume()
}
self.emit(Events.VISIBLE)
} else {
if (options.isAutoPauseEnabled() && (self.isCountingDown() || self.isRecording())) {
self.pause('document invisible')
}
self.emit(Events.INVISIBLE)
}
}
})
if (options.enableSpace) {
window.addEventListener('keypress', function (e) {
var tagName = e.target.tagName
if (tagName !== 'INPUT' && tagName !== 'TEXTAREA') {
var code = e.keyCode ? e.keyCode : e.which
if (code === 32) {
e.preventDefault()
if (options.enablePause) {
visuals.pauseOrResume()
} else {
visuals.recordOrStop()
}
}
}
})
}
// better to keep the one and only error listeners
// at one spot, here, because unload() will do a removeAllListeners()
self
.on(Events.ERROR, function (err) {
processError(err)
unloadChildren(err)
if (err.removeDimensions && err.removeDimensions()) {
removeDimensions()
}
})
.on(Events.LOADED_META_DATA, function () {
correctDimensions()
})
}
function validateOptions () {
if (options.hasDefinedWidth() && options.video.width % 2 !== 0) {
throw VideomailError.create('Width must be divisible by two.')
}
if (options.hasDefinedHeight() && options.video.height % 2 !== 0) {
throw VideomailError.create('Height must be divisible by two.')
}
}
// this will just set the width but not the height because
// it can be a form with more inputs elements
function correctDimensions () {
var width = visuals.getRecorderWidth(true)
if (width < 1) {
throw VideomailError.create('Recorder width cannot be less than 1!')
} else {
containerElement.style.width = width + 'px'
}
}
function removeDimensions () {
containerElement.style.width = 'auto'
}
function unloadChildren (e) {
visuals.unload(e)
buttons.unload()
self.endWaiting()
}
function hideMySelf () {
hidden(containerElement, true)
}
// fixes https://github.com/binarykitchen/videomail-client/issues/71
function trimEmail (email) {
return email.replace(/(^[,\s]+)|([,\s]+$)/g, '')
}
function submitVideomail (formData, method, cb) {
var FORM_FIELDS = {
'subject': options.selectors.subjectInputName,
'from': options.selectors.fromInputName,
'to': options.selectors.toInputName,
'body': options.selectors.bodyInputName,
'key': options.selectors.keyInputName,
'parentKey': options.selectors.parentKeyInputName
}
var videomailFormData = {}
Object.keys(FORM_FIELDS).forEach(function (key) {
if (formData.hasOwnProperty(FORM_FIELDS[key])) {
videomailFormData[key] = formData[FORM_FIELDS[key]]
}
})
if (videomailFormData.from) {
videomailFormData.from = trimEmail(videomailFormData.from)
}
if (videomailFormData.to) {
videomailFormData.to = trimEmail(videomailFormData.to)
}
// when method is undefined, treat it as a post
if (isPost(method) || !method) {
videomailFormData.recordingStats = visuals.getRecordingStats()
videomailFormData.width = visuals.getRecorderWidth(true)
videomailFormData.height = visuals.getRecorderHeight(true)
resource.post(videomailFormData, cb)
} else if (isPut(method)) { resource.put(videomailFormData, cb) }
}
function submitForm (formData, videomailResponse, url, cb) {
formData[options.selectors.aliasInputName] = videomailResponse.videomail.alias
resource.form(formData, url, cb)
}
function finalizeSubmissions (err, method, videomail, response, formResponse) {
self.endWaiting()
if (err) {
self.emit(Events.ERROR, err)
} else {
submitted = true
// merge two json response bodies to fake as if it were only one request
if (formResponse && formResponse.body) {
Object.keys(formResponse.body).forEach(function (key) {
response[key] = formResponse.body[key]
})
}
self.emit(
Events.SUBMITTED,
videomail,
response
)
if (formResponse && formResponse.type === 'text/html' && formResponse.text) {
// server replied with HTML contents - display these
document.body.innerHTML = formResponse.text
// todo: figure out how to fire dom's onload event again
// todo: or how to run all the scripts over again
}
}
}
this.addPlayerDimensions = function (videomail, element) {
try {
videomail.playerHeight = this.calculateHeight({
responsive: true,
videoWidth: videomail.width,
ratio: videomail.height / videomail.width
}, element)
videomail.playerWidth = this.calculateWidth({
responsive: true,
videoHeight: videomail.playerHeight,
ratio: videomail.height / videomail.width
})
return videomail
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
this.limitWidth = function (width) {
return Dimension.limitWidth(containerElement, width)
}
this.limitHeight = function (height) {
return Dimension.limitHeight(height)
}
this.calculateWidth = function (fnOptions) {
return Dimension.calculateWidth(merge.recursive(options, fnOptions))
}
this.calculateHeight = function (fnOptions, element) {
if (!element) {
if (containerElement) {
element = containerElement
} else {
// better than nothing
element = document.body
}
}
return Dimension.calculateHeight(element, merge.recursive(options, fnOptions))
}
this.areVisualsHidden = function () {
return visuals.isHidden()
}
this.hasElement = function () {
return !!containerElement
}
this.build = function () {
debug('Container: build()')
try {
containerElement = document.getElementById(options.selectors.containerId)
// only build when a container element hast been found, otherwise
// be silent and do nothing
if (containerElement) {
options.insertCss && prependDefaultCss()
!built && initEvents()
validateOptions()
correctDimensions()
buildForm()
buildChildren()
if (!hasError) {
built = true
self.emit(Events.BUILT)
}
} else {
debug('Container: no container element with ID ' + options.selectors.containerId + ' found. Do nothing.')
}
} catch (exc) {
if (built) {
self.emit(Events.ERROR, exc)
} else {
throw exc
}
}
}
this.getSubmitButton = function () {
return buttons.getSubmitButton()
}
this.querySelector = function (selector) {
return containerElement.querySelector(selector)
}
this.beginWaiting = function () {
htmlElement.classList && htmlElement.classList.add('wait')
}
this.endWaiting = function () {
htmlElement.classList && htmlElement.classList.remove('wait')
}
this.appendChild = function (child) {
containerElement.appendChild(child)
}
this.insertBefore = function (child, reference) {
containerElement.insertBefore(child, reference)
}
this.unload = function (e) {
debug('Container: unload()', e)
try {
unloadChildren(e)
this.removeAllListeners()
built = submitted = false
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
this.show = function () {
if (containerElement) {
hidden(containerElement, false)
visuals.show()
if (!hasError) {
var paused = self.isPaused()
if (paused) {
buttons.adjustButtonsForPause()
}
// since https://github.com/binarykitchen/videomail-client/issues/60
// we hide areas to make it easier for the user
buttons.show()
if (self.isReplayShown()) {
self.emit(Events.PREVIEW)
} else {
self.emit(Events.FORM_READY, {paused: paused})
}
}
}
}
this.hide = function () {
hasError = false
this.isRecording() && this.pause()
visuals.hide()
if (submitted) {
buttons.hide()
hideMySelf()
}
}
this.showReplayOnly = function () {
hasError = false
this.isRecording() && this.pause()
visuals.showReplayOnly()
submitted && buttons.hide()
}
this.isNotifying = function () {
return visuals.isNotifying()
}
this.isPaused = function () {
return visuals.isPaused()
}
this.pause = function (params) {
visuals.pause(params)
}
this.startOver = function () {
try {
submitted = false
form.show()
visuals.back(this.show)
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
// this code needs a good rewrite :(
this.validate = function (force) {
var runValidation = true
var valid
if (!options.enableAutoValidation) {
runValidation = false
lastValidation = true // needed so that it can be submitted anyway, see submit()
} else if (force) {
runValidation = force
} else if (self.isNotifying()) {
runValidation = false
} else if (visuals.isConnected()) {
runValidation = visuals.isUserMediaLoaded() || visuals.isReplayShown()
} else if (visuals.isConnecting()) {
runValidation = false
}
if (runValidation) {
this.emit(Events.VALIDATING)
var visualsValid = visuals.validate() && buttons.isRecordAgainButtonEnabled()
var whyInvalid
if (form) {
valid = form.validate()
if (valid) {
if (!this.areVisualsHidden() && !visualsValid) {
if (this.isReady() || this.isRecording() || this.isPaused() || this.isCountingDown()) {
valid = false
}
if (!valid) { whyInvalid = 'Video is not recorded' }
}
} else {
var invalidInput = form.getInvalidElement()
if (invalidInput) {
whyInvalid = 'Form input named ' + invalidInput.name + ' is invalid'
} else {
whyInvalid = 'Form input(s() are invalid'
}
}
} else { valid = visualsValid }
if (valid) {
this.emit(Events.VALID)
} else {
this.emit(Events.INVALID, whyInvalid)
}
lastValidation = valid
}
return valid
}
this.disableForm = function (buttonsToo) {
form && form.disable(buttonsToo)
}
this.enableForm = function (buttonsToo) {
form && form.enable(buttonsToo)
}
this.hasForm = function () {
return !!form
}
this.isReady = function () {
return buttons.isRecordButtonEnabled()
}
function isPost (method) {
return method && method.toUpperCase() === 'POST'
}
function isPut (method) {
return method && method.toUpperCase() === 'PUT'
}
this.submitAll = function (formData, method, url) {
this.beginWaiting()
this.disableForm(true)
this.emit(Events.SUBMITTING)
var post = isPost(method)
// a closure so that we can access method
var submitVideomailCallback = function (err1, videomail, videomailResponse) {
if (err1) {
finalizeSubmissions(err1, method, videomail, videomailResponse)
} else if (post) {
// for now, accept POSTs only which have an URL unlike null and
// treat all other submissions as direct submissions
if (!url || url === '') {
// figure out URL automatically then
url = document.baseURI
}
submitForm(formData, videomailResponse, url, function (err2, formResponse) {
finalizeSubmissions(err2, method, videomail, videomailResponse, formResponse)
})
} else {
// it's a direct submission
finalizeSubmissions(null, method, videomail, videomailResponse)
}
}
submitVideomail(formData, method, submitVideomailCallback)
}
this.isBuilt = function () {
return built
}
this.isReplayShown = function () {
return visuals.isReplayShown()
}
this.isDirty = function () {
var isDirty = false
if (form) {
if (visuals.isRecorderUnloaded()) {
isDirty = false
} else if (this.isReplayShown() || this.isPaused()) {
isDirty = true
}
}
return isDirty
}
this.getReplay = function () {
return visuals.getReplay()
}
this.isOutsideElementOf = function (element) {
return element.parentNode !== containerElement && element !== containerElement
}
this.hideForm = function () {
form.hide()
}
this.loadForm = function (videomail) {
form.loadVideomail(videomail)
this.validate()
}
this.enableAudio = function () {
options.setAudioEnabled(true)
this.emit(Events.ENABLING_AUDIO)
}
this.disableAudio = function () {
options.setAudioEnabled(false)
this.emit(Events.DISABLING_AUDIO)
}
this.submit = function () {
lastValidation && form && form.doTheSubmit()
}
this.isCountingDown = visuals.isCountingDown.bind(visuals)
this.isRecording = visuals.isRecording.bind(visuals)
this.record = visuals.record.bind(visuals)
this.resume = visuals.resume.bind(visuals)
this.stop = visuals.stop.bind(visuals)
this.recordAgain = visuals.recordAgain.bind(visuals)
}
util.inherits(Container, EventEmitter)
module.exports = Container
},{"./../events":375,"./../resource":377,"./../styles/css/main.min.css.js":378,"./../util/eventEmitter":382,"./../util/videomailError":387,"./buttons":388,"./dimension":390,"./form":391,"./visuals":393,"document-visibility":308,"hidden":320,"insert-css":326,"merge-recursive":335,"util":368}],390:[function(require,module,exports){
var numberIsInteger = require('number-is-integer')
var VideomailError = require('./../util/videomailError')
function getOuterWidth (element) {
var rect = element.getBoundingClientRect()
return rect.right - rect.left
}
function figureMinHeight (height, options) {
if (options.hasDefinedHeight()) {
if (!height) {
height = options.video.height
} else {
height = Math.min(options.video.height, height)
}
}
if (numberIsInteger(height) && height < 1) {
throw VideomailError.create(
'Got a video height less than 1 (' +
height +
') while figuring out the minimum!'
)
}
// just return it, can be "auto"
return height
}
module.exports = {
limitWidth: function (element, width) {
var outerWidth = getOuterWidth(element)
var limitedWidth = outerWidth > 0 && outerWidth < width ? outerWidth : width
if (numberIsInteger(limitedWidth) && limitedWidth < 1) {
throw VideomailError.create('Limited width cannot be less than 1!')
} else {
return limitedWidth
}
},
// this is difficult to compute and is not entirely correct.
// but good enough for now to ensure some stability.
limitHeight: function (height) {
if (numberIsInteger(height) && height < 1) {
throw VideomailError.create('Passed limit-height argument cannot be less than 1!')
} else {
var limitedHeight = Math.min(
height,
document.body.scrollHeight,
document.documentElement.clientHeight
)
if (limitedHeight < 1) {
throw VideomailError.create('Limited height cannot be less than 1!')
} else {
return limitedHeight
}
}
},
calculateWidth: function (options) {
var height = options.videoHeight || null
var ratio = options.ratio || options.getRatio()
height = figureMinHeight(height, options)
if (options.responsive) { height = this.limitHeight(height) }
if (numberIsInteger(height) && height < 1) {
throw VideomailError.create('Height cannot be smaller than 1 when calculating width.')
} else {
var calculatedWidth = parseInt(height / ratio)
if (calculatedWidth < 1) {
throw VideomailError.create('Calculated width cannot be smaller than 1!')
} else {
return calculatedWidth
}
}
},
calculateHeight: function (element, options) {
var width = options.videoWidth || null
var height
var ratio = options.ratio || options.getRatio()
if (options.hasDefinedWidth()) { width = options.video.width }
if (numberIsInteger(width) && width < 1) {
throw VideomailError.create('Unable to calculate height when width is less than 1.')
} else if (options.responsive) {
width = this.limitWidth(element, width)
}
if (width) { height = parseInt(width * ratio) }
if (numberIsInteger(height) && height < 1) {
throw VideomailError.create('Just calculated a height less than 1 which is wrong.')
} else {
return figureMinHeight(height, options)
}
}
}
},{"./../util/videomailError":387,"number-is-integer":336}],391:[function(require,module,exports){
var h = require('hyperscript')
var util = require('util')
var hidden = require('hidden')
var getFormData = require('get-form-data')
var Events = require('./../events')
var EventEmitter = require('./../util/eventEmitter')
var VideomailError = require('./../util/videomailError')
var Form = function (container, formElement, options) {
EventEmitter.call(this, options, 'Form')
var self = this
var disableContainerValidation,
keyInput
function getData () {
return getFormData(formElement)
}
this.loadVideomail = function (videomail) {
var limit = formElement.elements.length
var input,
name
for (var i = 0; i < limit; i++) {
input = formElement.elements[i]
name = input.name
if (videomail[name]) { input.value = videomail[name] }
if (name === options.selectors.subjectInputName ||
name === options.selectors.bodyInputName) {
input.disabled = true
}
}
formElement.setAttribute('method', 'put')
}
function isNotButton (element) {
return element.tagName !== 'BUTTON' && element.type !== 'submit'
}
function setDisabled (disabled, buttonsToo) {
var limit = formElement.elements.length
for (var i = 0; i < limit; i++) {
if (buttonsToo || (!buttonsToo && isNotButton(formElement.elements[i]))) {
formElement.elements[i].disabled = disabled
}
}
}
function hideAll () {
var limit = formElement.elements.length
for (var i = 0; i < limit; i++) {
hidden(formElement.elements[i], true)
}
hidden(formElement, true)
}
function getInputElements () {
return formElement.querySelectorAll('input, textarea')
}
function getSelectElements () {
return formElement.querySelectorAll('select')
}
this.disable = function (buttonsToo) {
setDisabled(true, buttonsToo)
}
this.enable = function (buttonsToo) {
setDisabled(false, buttonsToo)
}
this.build = function () {
if (options.enableAutoValidation) {
var inputElements = getInputElements()
var inputElement
for (var i = 0, len = inputElements.length; i < len; i++) {
inputElement = inputElements[i]
if (inputElement.type === 'radio') {
inputElement.addEventListener('change', function () {
container.validate()
})
} else {
inputElement.addEventListener('input', function () {
container.validate()
})
}
// because of angular's digest cycle, validate again when it became invalid
inputElement.addEventListener('invalid', function () {
if (!disableContainerValidation) { container.validate() }
})
}
var selectElements = getSelectElements()
for (var j = 0, len2 = selectElements.length; j < len2; j++) {
selectElements[j].addEventListener('change', function () {
container.validate()
})
}
}
keyInput = formElement.querySelector('input[name="' + options.selectors.keyInputName + '"]')
if (!keyInput) {
keyInput = h('input', {
name: options.selectors.keyInputName,
type: 'hidden'
})
formElement.appendChild(keyInput)
}
this.on(Events.PREVIEW, function (videomailKey) {
// beware that preview doesn't always come with a key, i.E.
// container.show() can emit PREVIEW without a key when a replay already exists
// (can happen when showing - hiding - showing videomail over again)
// only emit error if key is missing AND the input has no key (value) yet
if (!videomailKey && !keyInput.value) {
self.emit(Events.ERROR, VideomailError.create('Videomail key for preview is missing!'))
} else if (videomailKey) {
keyInput.value = videomailKey
}
// else
// leave as it and use existing keyInput.value
})
// fixes https://github.com/binarykitchen/videomail-client/issues/91
this.on(Events.GOING_BACK, function () {
keyInput.value = null
})
this.on(Events.ERROR, function (err) {
// since https://github.com/binarykitchen/videomail-client/issues/60
// we hide areas to make it easier for the user to process an error
// (= less distractions)
if (err.hideForm && err.hideForm() && options.adjustFormOnBrowserError) {
hideAll()
} else if (err.hideButtons && err.hideButtons() && options.adjustFormOnBrowserError) {
hideSubmitButton()
}
})
this.on(Events.BUILT, function () {
startListeningToSubmitEvents()
})
}
function hideSubmitButton () {
var submitButton = self.findSubmitButton()
hidden(submitButton, true)
}
function startListeningToSubmitEvents () {
var submitButton = container.getSubmitButton()
submitButton.addEventListener('click', self.doTheSubmit.bind(self))
}
this.doTheSubmit = function (e) {
// when videomail-client is hidden, leave the form handling as it and
// do not mess with it at all
if (!container.areVisualsHidden()) {
e && e.preventDefault()
// only adjust submission when there is a container, otherwise
// do nothing and leave as it for robustness
if (container.hasElement()) {
container.submitAll(
getData(),
formElement.getAttribute('method'),
formElement.getAttribute('action')
)
}
return false // important to stop submission
}
}
this.getInvalidElement = function () {
var inputElements = getInputElements()
for (var i = 0, len = inputElements.length; i < len; i++) {
if (!inputElements[i].validity.valid) { return inputElements[i] }
}
var selectElements = getSelectElements()
for (var j = 0, len2 = selectElements.length; j < len2; j++) {
if (!selectElements[i].validity.valid) { return selectElements[j] }
}
return null
}
this.validate = function () {
// prevents endless validation loop
disableContainerValidation = true
var formIsValid = formElement.checkValidity()
disableContainerValidation = false
return formIsValid
}
this.findSubmitButton = function () {
return formElement.querySelector("[type='submit']")
}
this.hide = function () {
formElement && hidden(formElement, true)
}
this.show = function () {
formElement && hidden(formElement, false)
}
}
util.inherits(Form, EventEmitter)
module.exports = Form
},{"./../events":375,"./../util/eventEmitter":382,"./../util/videomailError":387,"get-form-data":316,"hidden":320,"hyperscript":322,"util":368}],392:[function(require,module,exports){
// enhances options with useful functions we can reuse everywhere
module.exports = {
addFunctions: function (options) {
var audioEnabled = options.audio && options.audio.enabled
options.hasDefinedHeight = function () {
return options.video.height && options.video.height !== 'auto'
}
options.hasDefinedWidth = function () {
return options.video.width && options.video.width !== 'auto'
}
options.hasDefinedDimension = function () {
return options.hasDefinedWidth() || options.hasDefinedHeight()
}
options.hasDefinedDimensions = function () {
return options.hasDefinedWidth() && options.hasDefinedHeight()
}
options.getRatio = function () {
var ratio = 1 // just a default one when no computations are possible
if (options.hasDefinedDimensions()) { ratio = options.video.height / options.video.width }
return ratio
}
options.isAudioEnabled = function () {
return audioEnabled
}
options.setAudioEnabled = function (enabled) {
audioEnabled = enabled
}
options.isAutoPauseEnabled = function () {
return options.enableAutoPause && options.enablePause
}
}
}
},{}],393:[function(require,module,exports){
var util = require('util')
var h = require('hyperscript')
var hidden = require('hidden')
var Replay = require('./visuals/replay')
var Recorder = require('./visuals/recorder')
var Notifier = require('./visuals/notifier')
var RecorderInsides = require('./visuals/inside/recorderInsides')
var EventEmitter = require('./../util/eventEmitter')
var Events = require('./../events')
var Visuals = function (container, options) {
EventEmitter.call(this, options, 'Visuals')
var self = this
var replay = new Replay(this, options)
var recorder = new Recorder(this, replay, options)
var recorderInsides = new RecorderInsides(this, options)
var notifier = new Notifier(this, options)
var debug = options.debug
var visualsElement
var built
function buildNoScriptTag () {
var noScriptElement = container.querySelector('noscript')
if (!noScriptElement) {
noScriptElement = h('noscript')
noScriptElement.innerHTML = 'Please enable Javascript'
visualsElement.appendChild(noScriptElement)
}
}
function buildChildren () {
debug('Visuals: buildChildren()')
buildNoScriptTag()
notifier.build()
recorderInsides.build()
replay.build()
}
function initEvents () {
self
.on(Events.USER_MEDIA_READY, function () {
built = true
self.endWaiting()
container.enableForm(false)
})
.on(Events.PREVIEW, function () {
self.endWaiting()
})
.on(Events.BLOCKING, function (blockingOptions) {
if (!blockingOptions.hideForm && !options.adjustFormOnBrowserError) {
// do nothing, user still can enter form inputs
// can be useful when you are on i.E. seeflow's contact page and
// still want to tick off the webcam option
} else {
container.disableForm(true)
}
})
.on(Events.PREVIEW_SHOWN, function () {
container.validate(true)
})
.on(Events.LOADED_META_DATA, function () {
correctDimensions()
})
.on(Events.ERROR, function (err) {
if (err.removeDimensions && err.removeDimensions()) {
removeDimensions()
}
})
}
function correctDimensions () {
visualsElement.style.width = self.getRecorderWidth(true) + 'px'
visualsElement.style.height = self.getRecorderHeight(true) + 'px'
}
function removeDimensions () {
visualsElement.style.width = 'auto'
visualsElement.style.height = 'auto'
}
function isRecordable () {
return !self.isNotifying() && !replay.isShown() && !self.isCountingDown()
}
this.isCountingDown = function () {
return recorderInsides.isCountingDown()
}
this.build = function () {
visualsElement = container.querySelector('.' + options.selectors.visualsClass)
if (!visualsElement) {
visualsElement = h('div.' + options.selectors.visualsClass)
var buttonsElement = container.querySelector('.' + options.selectors.buttonsClass)
// make sure it's placed before the buttons
if (buttonsElement) {
container.insertBefore(visualsElement, buttonsElement)
} else {
container.appendChild(visualsElement)
}
}
visualsElement.classList.add('visuals')
hidden(visualsElement, true)
correctDimensions()
!built && initEvents()
buildChildren()
// needed for replay handling and container.isParentElementOf()
self.parentNode = visualsElement.parentNode
built = true
}
this.querySelector = function (selector) {
return visualsElement && visualsElement.querySelector(selector)
}
this.appendChild = function (child) {
visualsElement && visualsElement.appendChild(child)
}
this.removeChild = function (child) {
visualsElement.removeChild(child)
}
this.reset = function () {
this.endWaiting()
recorder.reset()
}
this.beginWaiting = function () {
container.beginWaiting()
}
this.endWaiting = function () {
container.endWaiting()
}
this.stop = function (params) {
recorder.stop(params)
recorderInsides.hidePause()
}
this.back = function (cb) {
replay.hide()
notifier.hide()
recorder.back(cb)
}
this.recordAgain = function () {
this.back(function () {
self.once(Events.USER_MEDIA_READY, function () {
self.record()
})
})
}
this.unload = function (e) {
try {
recorder.unload(e)
recorderInsides.unload(e)
replay.unload(e)
built = false
} catch (exc) {
this.emit(Events.ERROR, exc)
}
}
this.isNotifying = function () {
return notifier.isVisible()
}
this.isReplayShown = function () {
return replay.isShown()
}
this.pause = function (params) {
recorder.pause(params)
recorderInsides.showPause()
}
this.resume = function () {
if (recorderInsides.isCountingDown()) {
recorderInsides.resumeCountdown()
} else {
recorder.resume()
}
recorderInsides.hidePause()
}
this.pauseOrResume = function () {
if (isRecordable.call(this)) {
if (this.isRecording()) {
this.pause()
} else if (recorder.isPaused()) {
this.resume()
} else if (recorder.isReady()) {
this.record()
}
}
}
this.recordOrStop = function () {
if (isRecordable()) {
if (this.isRecording()) {
this.stop()
} else if (recorder.isReady()) {
this.record()
}
}
}
this.record = function () {
if (options.video.countdown) {
this.emit(Events.COUNTDOWN)
recorderInsides.startCountdown(recorder.record.bind(recorder))
} else { recorder.record() }
}
this.getRecorder = function () {
return recorder
}
this.getReplay = function () {
return replay
}
this.validate = function () {
return recorder.validate() && this.isReplayShown()
}
this.getRecordingStats = function () {
return recorder.getRecordingStats()
}
this.getAudioSampleRate = function () {
return recorder.getAudioSampleRate()
}
this.isPaused = function () {
return recorder.isPaused()
}
this.error = function (err) {
notifier.error(err)
}
this.hide = function () {
if (visualsElement) {
hidden(visualsElement, true)
this.emit(Events.HIDE)
}
}
this.isHidden = function () {
if (!built) {
return true
} else if (visualsElement) {
return hidden(visualsElement)
}
}
this.show = function () {
!this.isReplayShown() && recorder.build()
visualsElement && hidden(visualsElement, false)
}
this.showReplayOnly = function () {
!this.isReplayShown() && replay.show()
self.show()
recorder.hide()
notifier.hide()
}
this.isRecorderUnloaded = function () {
return recorder.isUnloaded()
}
this.isConnecting = function () {
return recorder.isConnecting()
}
this.getRecorderWidth = function (responsive) {
return recorder.getRecorderWidth(responsive)
}
this.getRecorderHeight = function (responsive) {
return recorder.getRecorderHeight(responsive)
}
this.limitWidth = function (width) {
return container.limitWidth(width)
}
this.limitHeight = function (height) {
return container.limitHeight(height)
}
this.calculateWidth = function (options) {
return container.calculateWidth(options)
}
this.calculateHeight = function (options) {
return container.calculateHeight(options)
}
this.getReplay = function () {
return replay
}
this.getBoundingClientRect = function () {
return visualsElement.getBoundingClientRect()
}
this.checkTimer = function (intervalSum) {
recorderInsides.checkTimer(intervalSum)
}
this.isReplayShown = replay.isShown.bind(replay)
this.hideReplay = replay.hide.bind(replay)
this.hideRecorder = recorder.hide.bind(recorder)
this.isRecording = recorder.isRecording.bind(recorder)
this.isUserMediaLoaded = recorder.isUserMediaLoaded.bind(recorder)
this.isConnected = recorder.isConnected.bind(recorder)
}
util.inherits(Visuals, EventEmitter)
module.exports = Visuals
},{"./../events":375,"./../util/eventEmitter":382,"./visuals/inside/recorderInsides":398,"./visuals/notifier":399,"./visuals/recorder":400,"./visuals/replay":401,"hidden":320,"hyperscript":322,"util":368}],394:[function(require,module,exports){
var h = require('hyperscript')
var hidden = require('hidden')
module.exports = function (visuals, options) {
var self = this
var countdownElement,
intervalId,
countdown,
paused
function fire (cb) {
self.unload()
self.hide()
// keep all callbacks async
setTimeout(function () {
cb()
}, 0)
}
function countBackward (cb) {
if (!paused) {
options.debug('Countdown', countdown)
countdown--
if (countdown < 1) {
fire(cb)
} else {
countdownElement.innerHTML = countdown
}
}
}
this.start = function (cb) {
countdownElement.innerHTML = countdown = options.video.countdown
this.show()
intervalId = setInterval(countBackward.bind(this, cb), 950)
}
this.pause = function () {
paused = true
}
this.resume = function () {
paused = false
}
this.build = function () {
countdownElement = visuals.querySelector('.countdown')
if (!countdownElement) {
countdownElement = h('p.countdown')
this.hide()
visuals.appendChild(countdownElement)
} else { this.hide() }
}
this.show = function () {
hidden(countdownElement, false)
}
this.isCountingDown = function () {
return !!intervalId
}
this.unload = function () {
clearInterval(intervalId)
paused = false
intervalId = null
}
this.hide = function () {
hidden(countdownElement, true)
this.unload()
}
}
},{"hidden":320,"hyperscript":322}],395:[function(require,module,exports){
var h = require('hyperscript')
var hidden = require('hidden')
var VideomailError = require('./../../../../util/videomailError')
module.exports = function (visuals, options) {
if (!options.text.pausedHeader) { throw VideomailError.create('Paused header cannot be empty', options) }
var pausedBlockElement,
pausedHeaderElement,
pausedHintElement
this.build = function () {
pausedBlockElement = visuals.querySelector('.paused')
pausedHeaderElement = visuals.querySelector('.pausedHeader')
pausedHintElement = visuals.querySelector('.pausedHint')
if (!pausedHeaderElement) {
pausedBlockElement = h('div.paused')
pausedHeaderElement = h('p.pausedHeader')
pausedHintElement = h('p.pausedHint')
this.hide()
pausedHeaderElement.innerHTML = options.text.pausedHeader
pausedHintElement.innerHTML = options.text.pausedHint
pausedBlockElement.appendChild(pausedHeaderElement)
pausedBlockElement.appendChild(pausedHintElement)
visuals.appendChild(pausedBlockElement)
} else {
this.hide()
pausedHeaderElement.innerHTML = options.text.pausedHeader
pausedHintElement.innerHTML = options.text.pausedHint
}
}
this.hide = function () {
hidden(pausedBlockElement, true)
}
this.show = function () {
hidden(pausedBlockElement, false)
}
}
},{"./../../../../util/videomailError":387,"hidden":320,"hyperscript":322}],396:[function(require,module,exports){
var h = require('hyperscript')
var hidden = require('hidden')
module.exports = function (visuals) {
var recordNoteElement
this.build = function () {
recordNoteElement = visuals.querySelector('.recordNote')
if (!recordNoteElement) {
recordNoteElement = h('p.recordNote')
this.hide()
visuals.appendChild(recordNoteElement)
} else { this.hide() }
}
this.stop = function () {
this.hide()
recordNoteElement.classList.remove('near')
recordNoteElement.classList.remove('nigh')
}
this.setNear = function () {
recordNoteElement.classList.add('near')
}
this.setNigh = function () {
recordNoteElement.classList.add('nigh')
}
this.hide = function () {
hidden(recordNoteElement, true)
}
this.show = function () {
hidden(recordNoteElement, false)
}
}
},{"hidden":320,"hyperscript":322}],397:[function(require,module,exports){
var h = require('hyperscript')
var hidden = require('hidden')
module.exports = function (visuals, recordNote, options) {
var recordTimerElement
var nearComputed = false
var endNighComputed = false
var started
var countdown
function pad (n) {
return n < 10 ? '0' + n : n
}
function thresholdReached (secs, threshold) {
return secs >= options.video.limitSeconds * threshold
}
function isNear (secs) {
if (!nearComputed && thresholdReached(secs, 0.6)) {
nearComputed = true
return true
} else { return false }
}
function endIsNigh (secs) {
if (!endNighComputed && thresholdReached(secs, 0.8)) {
endNighComputed = true
return true
} else { return false }
}
function setNear () {
recordTimerElement.classList.add('near')
}
function setNigh () {
recordTimerElement.classList.add('nigh')
}
this.check = function (opts) {
var newCountdown = getStartSeconds() - Math.floor(opts.intervalSum / 1e3)
// performance optimisation (another reason we need react here!)
if (newCountdown !== countdown) {
countdown = newCountdown
update()
countdown < 1 && visuals.stop(true)
}
}
function update () {
var mins = parseInt(countdown / 60, 10)
var secs = countdown - mins * 60
if (!nearComputed || !endNighComputed) {
var remainingSeconds = options.video.limitSeconds - countdown
if (isNear(remainingSeconds)) {
recordNote.setNear()
setNear()
options.debug('End is near, ' + countdown + ' seconds to go')
} else if (endIsNigh(remainingSeconds)) {
recordNote.setNigh()
setNigh()
options.debug('End is nigh, ' + countdown + ' seconds to go')
}
}
recordTimerElement.innerHTML = mins + ':' + pad(secs)
}
function hide () {
hidden(recordTimerElement, true)
}
function show () {
recordTimerElement.classList.remove('near')
recordTimerElement.classList.remove('nigh')
hidden(recordTimerElement, false)
}
function getSecondsRecorded () {
return getStartSeconds() - countdown
}
function getStartSeconds () {
return options.video.limitSeconds
}
this.start = function () {
countdown = getStartSeconds()
nearComputed = endNighComputed = false
started = true
update()
show()
}
this.pause = function () {
recordNote.hide()
}
this.resume = function () {
recordNote.show()
}
function isStopped () {
return countdown === null
}
this.stop = function () {
if (!isStopped() && started) {
options.debug('Stopping record timer. Was recording for about ~' + getSecondsRecorded() + ' seconds.')
hide()
recordNote.stop()
countdown = null
started = false
}
}
this.build = function () {
recordTimerElement = visuals.querySelector('.recordTimer')
if (!recordTimerElement) {
recordTimerElement = h('p.recordTimer')
hide()
visuals.appendChild(recordTimerElement)
} else { hide() }
}
}
},{"hidden":320,"hyperscript":322}],398:[function(require,module,exports){
var util = require('util')
var Events = require('./../../../events')
var EventEmitter = require('./../../../util/eventEmitter')
var Countdown = require('./recorder/countdown')
var PausedNote = require('./recorder/pausedNote')
var RecordNote = require('./recorder/recordNote')
var RecordTimer = require('./recorder/recordTimer')
var RecorderInsides = function (visuals, options) {
EventEmitter.call(this, options, 'RecorderInsides')
var self = this
var recordNote = new RecordNote(visuals)
var recordTimer = new RecordTimer(visuals, recordNote, options)
var countdown,
pausedNote,
built
if (options.video.countdown) { countdown = new Countdown(visuals, options) }
if (options.enablePause) { pausedNote = new PausedNote(visuals, options) }
function startRecording () {
recordTimer.start()
}
function resumeRecording () {
recordTimer.resume()
}
function stopRecording () {
recordTimer.stop()
}
function pauseRecording () {
if (self.isCountingDown()) {
countdown.pause()
} else {
recordTimer.pause()
}
}
function onResetting () {
self.hidePause()
self.hideCountdown()
recordTimer.stop()
}
function initEvents () {
self
.on(Events.RECORDING, function () {
startRecording()
})
.on(Events.RESUMING, function () {
resumeRecording()
})
.on(Events.STOPPING, function () {
stopRecording()
})
.on(Events.PAUSED, function () {
pauseRecording()
})
.on(Events.RESETTING, onResetting)
.on(Events.HIDE, function () {
self.hideCountdown()
})
}
this.build = function () {
countdown && countdown.build()
pausedNote && pausedNote.build()
recordNote.build()
recordTimer.build()
!built && initEvents()
built = true
}
this.unload = function () {
countdown && countdown.unload()
built = false
}
this.showPause = function () {
pausedNote && pausedNote.show()
}
this.hidePause = function () {
pausedNote && pausedNote.hide()
}
this.hideCountdown = function () {
countdown && countdown.hide()
}
this.startCountdown = function (cb) {
countdown && countdown.start(cb)
}
this.resumeCountdown = function () {
countdown && countdown.resume()
}
this.isCountingDown = function () {
return countdown && countdown.isCountingDown()
}
this.checkTimer = function (intervalSum) {
recordTimer.check(intervalSum)
}
}
util.inherits(RecorderInsides, EventEmitter)
module.exports = RecorderInsides
},{"./../../../events":375,"./../../../util/eventEmitter":382,"./recorder/countdown":394,"./recorder/pausedNote":395,"./recorder/recordNote":396,"./recorder/recordTimer":397,"util":368}],399:[function(require,module,exports){
var util = require('util')
var h = require('hyperscript')
var hidden = require('hidden')
var EventEmitter = require('./../../util/eventEmitter')
var Events = require('./../../events')
var Notifier = function (visuals, options) {
EventEmitter.call(this, options, 'Notifier')
var self = this
var debug = options && options.debug
var notifyElement
var messageElement
var explanationElement
var entertainTimeoutId
var entertaining
var built
function onStopping (limitReached) {
var lead = ''
visuals.beginWaiting()
if (limitReached) {
debug('Limit reached')
lead += options.text.limitReached + '.<br/>'
}
lead += options.text.sending + ' …'
self.notify(lead, null, {
stillWait: true,
entertain: options.notifier.entertain
})
}
function onConnecting () {
self.notify('Connecting …')
}
function onLoadingUserMedia () {
self.notify('Loading webcam …')
}
function onProgress (frameProgress, sampleProgress) {
var overallProgress
if (options.isAudioEnabled()) {
overallProgress = 'Video: ' + frameProgress
if (sampleProgress) { overallProgress += ', Audio: ' + sampleProgress }
} else { overallProgress = frameProgress }
self.setExplanation(overallProgress)
}
function onBeginVideoEncoding () {
visuals.beginWaiting()
var lead = options.text.encoding + ' …'
self.notify(lead, null, {
stillWait: true,
entertain: options.notifier.entertain
})
hideExplanation()
}
function initEvents () {
debug('Notifier: initEvents()')
self
.on(Events.CONNECTING, function () {
onConnecting()
})
.on(Events.LOADING_USER_MEDIA, function () {
onLoadingUserMedia()
})
.on(Events.USER_MEDIA_READY, function () {
self.hide()
})
.on(Events.LOADED_META_DATA, function () {
correctDimensions()
})
.on(Events.PREVIEW, function () {
self.hide()
})
.on(Events.STOPPING, function (limitReached) {
onStopping(limitReached)
})
.on(Events.PROGRESS, function (frameProgress, sampleProgress) {
onProgress(frameProgress, sampleProgress)
})
.on(Events.BEGIN_VIDEO_ENCODING, function () {
onBeginVideoEncoding()
})
}
function correctDimensions () {
notifyElement.style.width = visuals.getRecorderWidth(true) + 'px'
notifyElement.style.height = visuals.getRecorderHeight(true) + 'px'
}
function show () {
notifyElement && hidden(notifyElement, false)
}
function runEntertainment () {
if (options.notifier.entertain) {
if (!entertaining) {
var randomBackgroundClass = Math.floor((Math.random() * options.notifier.entertainLimit) + 1)
notifyElement.className = 'notifier entertain ' +
options.notifier.entertainClass +
randomBackgroundClass
entertainTimeoutId = setTimeout(runEntertainment, options.notifier.entertainInterval)
entertaining = true
}
} else { cancelEntertainment() }
}
function cancelEntertainment () {
if (notifyElement) {
notifyElement.classList.remove('entertain')
}
clearTimeout(entertainTimeoutId)
entertainTimeoutId = null
entertaining = false
}
function setMessage (message, messageOptions) {
var problem = messageOptions.problem ? messageOptions.problem : false
if (messageElement) {
messageElement.innerHTML = (problem ? '☹ ' : '') + message
} else {
options.logger.warn(
'Unable to show following because messageElement is empty:',
message
)
}
}
this.error = function (err) {
var message = err.message ? err.message.toString() : err.toString()
var explanation = err.explanation ? err.explanation.toString() : null
if (!message) {
options.debug('Weird empty message generated for error', err)
}
self.notify(message, explanation, {
blocking: true,
problem: true,
hideForm: err.hideForm && err.hideForm(),
classList: err.getClassList && err.getClassList(),
removeDimensions: err.removeDimensions && err.removeDimensions()
})
}
this.setExplanation = function (explanation) {
if (!explanationElement) {
explanationElement = h('p')
if (notifyElement) {
notifyElement.appendChild(explanationElement)
} else {
options.logger.warn(
'Unable to show explanation because notifyElement is empty:',
explanation
)
}
}
explanationElement.innerHTML = explanation
hidden(explanationElement, false)
}
this.build = function () {
notifyElement = visuals.querySelector('.notifier')
if (!notifyElement) {
notifyElement = h('.notifier') // defaults to div
this.hide()
visuals.appendChild(notifyElement)
} else { this.hide() }
!built && initEvents()
built = true
}
function hideExplanation () {
if (explanationElement) {
explanationElement.innerHTML = null
hidden(explanationElement, true)
}
}
this.hide = function () {
cancelEntertainment()
if (notifyElement) {
hidden(notifyElement, true)
notifyElement.classList.remove('blocking')
}
if (messageElement) { messageElement.innerHTML = null }
hideExplanation()
}
this.isVisible = function () {
if (!built) { return false } else { return notifyElement && !hidden(notifyElement) }
}
this.notify = function (message, explanation, notifyOptions) {
if (!notifyOptions) {
notifyOptions = {}
}
var stillWait = notifyOptions.stillWait ? notifyOptions.stillWait : false
var entertain = notifyOptions.entertain ? notifyOptions.entertain : false
var blocking = notifyOptions.blocking ? notifyOptions.blocking : false
var hideForm = notifyOptions.hideForm ? notifyOptions.hideForm : false
var classList = notifyOptions.classList ? notifyOptions.classList : false
var removeDimensions = notifyOptions.removeDimensions ? notifyOptions.removeDimensions : false
if (!messageElement && notifyElement) {
messageElement = h('h2')
if (explanationElement) {
notifyElement.insertBefore(messageElement, explanationElement)
} else {
notifyElement.appendChild(messageElement)
}
}
if (notifyElement) {
// reset
if (!entertain) {
notifyElement.className = 'notifier'
}
if (classList) {
classList.forEach(function (className) {
notifyElement.classList.add(className)
})
}
if (removeDimensions) {
notifyElement.style.width = 'auto'
notifyElement.style.height = 'auto'
}
}
if (blocking) {
notifyElement && notifyElement.classList.add('blocking')
this.emit(Events.BLOCKING, {hideForm: hideForm})
} else {
this.emit(Events.NOTIFYING)
}
visuals.hideReplay()
visuals.hideRecorder()
setMessage(message, notifyOptions)
explanation && this.setExplanation(explanation)
if (entertain) {
runEntertainment()
} else {
cancelEntertainment()
}
show()
!stillWait && visuals.endWaiting()
}
}
util.inherits(Notifier, EventEmitter)
module.exports = Notifier
},{"./../../events":375,"./../../util/eventEmitter":382,"hidden":320,"hyperscript":322,"util":368}],400:[function(require,module,exports){
(function (Buffer){
var websocket = require('websocket-stream')
var Frame = require('canvas-to-buffer')
var util = require('util')
var h = require('hyperscript')
var hidden = require('hidden')
var animitter = require('animitter')
var UserMedia = require('./userMedia')
var Events = require('./../../events')
var Constants = require('./../../constants')
var EventEmitter = require('./../../util/eventEmitter')
var Browser = require('./../../util/browser')
var Humanize = require('./../../util/humanize')
var pretty = require('./../../util/pretty')
var VideomailError = require('./../../util/videomailError')
// credits http://1lineart.kulaone.com/#/
var PIPE_SYMBOL = '°º¤ø,¸¸,ø¤º°`°º¤ø,¸,ø¤°º¤ø,¸¸,ø¤º°`°º¤ø,¸ '
var Recorder = function (visuals, replay, options) {
EventEmitter.call(this, options, 'Recorder')
// validate some options this class needs
if (!options || !options.video || !options.video.fps) {
throw VideomailError.create('FPS must be defined', options)
}
var self = this
var browser = new Browser(options)
var debug = options.debug
var loop = null
var originalAnimationFrameObject
var samplesCount = 0
var framesCount = 0
var recordingStats = {}
var confirmedFrameNumber = 0
var confirmedSampleNumber = 0
var recorderElement
var userMedia
var userMediaTimeout
var retryTimeout
var bytesSum
var frameProgress
var sampleProgress
var canvas
var ctx
var userMediaLoaded
var userMediaLoading
var submitting
var unloaded
var stopTime
var stream
var connecting
var connected
var blocking
var built
var key
var waitingTime
var pingInterval
var frame
var recordingBufferLength
var recordingBuffer
function writeStream (buffer, opts) {
if (stream) {
if (stream.destroyed) {
self.emit(Events.ERROR, VideomailError.create(
'Already disconnected',
'Sorry, the connection to the server has been destroyed. Please reload. ' +
'Details of buffer: ' + buffer.toString(),
options
))
} else {
var onFlushedCallback = opts && opts.onFlushedCallback
try {
stream.write(buffer, function () {
onFlushedCallback && onFlushedCallback(opts)
})
} catch (exc) {
self.emit(Events.ERROR, VideomailError.create(
'Failed writing to server',
'stream.write() failed because of ' + pretty(exc),
options
))
}
}
}
}
function sendPings () {
pingInterval = window.setInterval(function () {
debug('Recorder: pinging...')
writeStream(Buffer.from(''))
}, options.timeouts.pingInterval)
}
function stopPings () {
clearInterval(pingInterval)
}
function onAudioSample (audioSample) {
samplesCount++
var audioBuffer = audioSample.toBuffer()
// if (options.verbose) {
// debug(
// 'Sample #' + samplesCount + ' (' + audioBuffer.length + ' bytes):'
// )
// }
writeStream(audioBuffer)
}
function show () {
recorderElement && hidden(recorderElement, false)
}
function onUserMediaReady () {
try {
debug('Recorder: onUserMediaReady()')
userMediaLoading = blocking = unloaded = submitting = false
userMediaLoaded = true
loop = createLoop()
show()
self.emit(Events.USER_MEDIA_READY, {paused: self.isPaused()})
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
function clearRetryTimeout () {
debug('Recorder: clearRetryTimeout()')
retryTimeout && clearTimeout(retryTimeout)
retryTimeout = null
}
function clearUserMediaTimeout () {
if (userMediaTimeout) {
debug('Recorder: clearUserMediaTimeout()')
userMediaTimeout && clearTimeout(userMediaTimeout)
userMediaTimeout = null
}
}
function calculateFrameProgress () {
return (confirmedFrameNumber / (framesCount || 1) * 100).toFixed(2) + '%'
}
function calculateSampleProgress () {
return (confirmedSampleNumber / (samplesCount || 1) * 100).toFixed(2) + '%'
}
function updateOverallProgress () {
// when progresses aren't initialized,
// then do a first calculation to avoid `infinite` or `null` displays
if (!frameProgress) {
frameProgress = calculateFrameProgress()
}
if (!sampleProgress) {
sampleProgress = calculateSampleProgress()
}
self.emit(
Events.PROGRESS,
frameProgress,
sampleProgress
)
}
function updateFrameProgress (args) {
confirmedFrameNumber = args.frame ? args.frame : confirmedFrameNumber
frameProgress = calculateFrameProgress()
updateOverallProgress()
}
function updateSampleProgress (args) {
confirmedSampleNumber = args.sample ? args.sample : confirmedSampleNumber
sampleProgress = calculateSampleProgress()
updateOverallProgress()
}
function preview (args) {
confirmedFrameNumber =
confirmedSampleNumber =
samplesCount =
framesCount = 0
sampleProgress =
frameProgress = null
key = args.key
if (args.mp4) {
replay.setMp4Source(
args.mp4 + Constants.SITE_NAME_LABEL + '/' + options.siteName + '/videomail.mp4',
true
)
}
if (args.webm) {
replay.setWebMSource(
args.webm + Constants.SITE_NAME_LABEL + '/' + options.siteName + '/videomail.webm',
true
)
}
self.hide()
self.emit(Events.PREVIEW, key, self.getRecorderWidth(true), self.getRecorderHeight(true))
// keep it for recording stats
waitingTime = Date.now() - stopTime
recordingStats.waitingTime = waitingTime
if (options.debug) {
debug(
'While recording, %s have been transferred and waiting time was %s',
Humanize.filesize(bytesSum, 2),
Humanize.toTime(waitingTime)
)
}
}
function initSocket (cb) {
if (!connected) {
connecting = true
debug('Recorder: initialising web socket to %s', options.socketUrl)
self.emit(Events.CONNECTING)
// https://github.com/maxogden/websocket-stream#binary-sockets
// we use query parameters here because we cannot set custom headers in web sockets,
// see https://github.com/websockets/ws/issues/467
var url2Connect =
options.socketUrl +
'?' +
encodeURIComponent(Constants.SITE_NAME_LABEL) +
'=' +
encodeURIComponent(options.siteName)
try {
// websocket options cannot be set on client side, only on server, see
// https://github.com/maxogden/websocket-stream/issues/116#issuecomment-296421077
stream = websocket(url2Connect, {
// see https://github.com/maxogden/websocket-stream/issues/117#issuecomment-298826011
objectMode: true
})
} catch (exc) {
connecting = connected = false
var err
if (typeof websocket === 'undefined') {
err = VideomailError.create('There is no websocket', 'Cause: ' + pretty(exc), options)
} else {
err = VideomailError.create(
'Failed to connect to server',
'Please upgrade your browser. Your current version does not seem to support websockets.',
options, {
browserProblem: true
}
)
}
self.emit(Events.ERROR, err)
}
if (stream) {
// // useful for debugging streams
//
// if (!stream.originalEmit) {
// stream.originalEmit = stream.emit
// }
//
// stream.emit = function (type) {
// if (stream) {
// debug(PIPE_SYMBOL + 'Debugging stream event:', type)
// var args = Array.prototype.slice.call(arguments, 0)
// return stream.originalEmit.apply(stream, args)
// }
// }
stream.on('close', function (err) {
debug(PIPE_SYMBOL + 'Stream has closed')
connecting = connected = false
if (err) {
self.emit(Events.ERROR, err || 'Unhandled websocket error')
} else {
self.emit(Events.DISCONNECTED)
// prevents from https://github.com/binarykitchen/videomail.io/issues/297 happening
cancelAnimationFrame()
}
})
stream.on('connect', function () {
debug(PIPE_SYMBOL + 'Stream *connect* event emitted')
if (!connected) {
connected = true
connecting = unloaded = false
self.emit(Events.CONNECTED)
debug('Asking for webcam permissons now.')
cb && cb()
}
})
stream.on('data', function (data) {
debug(PIPE_SYMBOL + 'Stream *data* event emitted')
var command
try {
command = JSON.parse(data.toString())
} catch (exc) {
debug('Failed to parse command:', exc)
self.emit(Events.ERROR, VideomailError.create(
'Invalid server command',
// toString() since https://github.com/binarykitchen/videomail.io/issues/288
'Contact us asap. Bad commmand was ' + data.toString() + '. ',
options
))
} finally {
executeCommand.call(self, command)
}
})
stream.on('error', function (err) {
debug(PIPE_SYMBOL + 'Stream *error* event emitted')
connecting = connected = false
self.emit(Events.ERROR, err)
})
// just experimental
stream.on('drain', function () {
debug(PIPE_SYMBOL + 'Stream *drain* event emitted (should not happen!)')
})
stream.on('preend', function () {
debug(PIPE_SYMBOL + 'Stream *preend* event emitted')
})
stream.on('end', function () {
debug(PIPE_SYMBOL + 'Stream *end* event emitted')
})
stream.on('drain', function () {
debug(PIPE_SYMBOL + 'Stream *drain* event emitted')
})
stream.on('pipe', function () {
debug(PIPE_SYMBOL + 'Stream *pipe* event emitted')
})
stream.on('unpipe', function () {
debug(PIPE_SYMBOL + 'Stream *unpipe* event emitted')
})
stream.on('resume', function () {
debug(PIPE_SYMBOL + 'Stream *resume* event emitted')
})
stream.on('uncork', function () {
debug(PIPE_SYMBOL + 'Stream *uncork* event emitted')
})
stream.on('readable', function () {
debug(PIPE_SYMBOL + 'Stream *preend* event emitted')
})
stream.on('prefinish', function () {
debug(PIPE_SYMBOL + 'Stream *preend* event emitted')
})
stream.on('finish', function () {
debug(PIPE_SYMBOL + 'Stream *preend* event emitted')
})
}
}
}
function showUserMedia () {
// use connected flag to prevent this from happening
// https://github.com/binarykitchen/videomail.io/issues/323
return connected && (isNotifying() || !isHidden() || blocking)
}
function userMediaErrorCallback (err) {
userMediaLoading = false
clearUserMediaTimeout()
debug(
'Recorder: userMediaErrorCallback()',
', Webcam characteristics:',
userMedia.getCharacteristics(),
', temporary err stack:',
(err && err.stack) || '(undefined)'
)
var errorListeners = self.listeners(Events.ERROR)
if (errorListeners.length) {
if (err.name !== VideomailError.MEDIA_DEVICE_NOT_SUPPORTED) {
self.emit(Events.ERROR, err)
} else {
// do not emit but retry since MEDIA_DEVICE_NOT_SUPPORTED can be a race condition
debug('Recorder: ignore user media error', err)
}
// retry after a while
retryTimeout = setTimeout(initSocket, options.timeouts.userMedia)
} else {
if (unloaded) {
// can happen that container is unloaded but some user media related callbacks
// are still in process. in that case ignore error.
debug('Recorder: already unloaded. Not going to throw error', err)
} else {
debug('Recorder: no error listeners attached but throwing error', err)
// weird situation, throw it instead of emitting since there are no error listeners
throw VideomailError.create(
err,
'Unable to process this error since there are no error listeners anymore.',
options
)
}
}
}
function getUserMediaCallback (localStream) {
debug('Recorder: getUserMediaCallback()')
if (showUserMedia()) {
try {
clearUserMediaTimeout()
userMedia.init(
localStream,
onUserMediaReady.bind(self),
onAudioSample.bind(self),
function (err) {
self.emit(Events.ERROR, err)
}
)
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
}
function loadGenuineUserMedia () {
if (!navigator) {
throw new Error('Navigator is missing!')
}
self.emit(Events.ASKING_WEBCAM_PERMISSION)
// https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// prefer the front camera (if one is available) over the rear one
var constraints = {
video: {
facingMode: 'user',
frameRate: {ideal: options.video.fps}
},
audio: options.isAudioEnabled()
}
if (options.hasDefinedWidth()) {
constraints.video.width = {ideal: options.video.width}
}
if (options.hasDefinedHeight()) {
constraints.video.height = {ideal: options.video.height}
}
debug('Recorder: navigator.mediaDevices.getUserMedia()')
navigator.mediaDevices
.getUserMedia(constraints)
.then(getUserMediaCallback)
.catch(userMediaErrorCallback)
} else {
debug('Recorder: navigator.getUserMedia()')
navigator.getUserMedia_({
video: true,
audio: options.isAudioEnabled()
}, getUserMediaCallback, userMediaErrorCallback)
}
}
function loadUserMedia () {
if (userMediaLoaded) {
debug('Recorder: skipping loadUserMedia() because it is already loaded')
onUserMediaReady()
return false
} else if (userMediaLoading) {
debug('Recorder: skipping loadUserMedia() because it is already asking for permission')
return false
}
debug('Recorder: loadUserMedia()')
self.emit(Events.LOADING_USER_MEDIA)
try {
userMediaTimeout = setTimeout(function () {
if (!self.isReady()) {
self.emit(Events.ERROR, browser.getNoAccessIssue())
}
}, options.timeouts.userMedia)
userMediaLoading = true
loadGenuineUserMedia()
} catch (exc) {
userMediaLoading = false
var errorListeners = self.listeners(Events.ERROR)
if (errorListeners.length) {
self.emit(Events.ERROR, exc)
} else {
debug('Recorder: no error listeners attached but throwing exception', exc)
throw exc // throw it further
}
}
}
function executeCommand (command) {
try {
debug(
'Server commanded: %s',
command.command,
command.args ? ', ' + JSON.stringify(command.args) : ''
)
switch (command.command) {
case 'ready':
if (!userMediaTimeout) { loadUserMedia() }
break
case 'preview':
preview(command.args)
break
case 'error':
this.emit(Events.ERROR, VideomailError.create(
'Oh no, server error!',
command.args.err.toString() || '(No explanation given)',
options
))
break
case 'confirmFrame':
updateFrameProgress(command.args)
break
case 'confirmSample':
updateSampleProgress(command.args)
break
case 'beginAudioEncoding':
this.emit(Events.BEGIN_AUDIO_ENCODING)
break
case 'beginVideoEncoding':
this.emit(Events.BEGIN_VIDEO_ENCODING)
break
default:
this.emit(Events.ERROR, 'Unknown server command: ' + command.command)
break
}
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
function isNotifying () {
return visuals.isNotifying()
}
function isHidden () {
return !recorderElement || hidden(recorderElement)
}
function writeCommand (command, args, cb) {
if (!cb && args && args.constructor === Function) {
cb = args
args = null
}
if (!connected) {
debug('Reconnecting for the command', command, '…')
initSocket(function () {
writeCommand(command, args)
cb && cb()
})
} else if (stream) {
debug('$ %s', command, args ? JSON.stringify(args) : '')
var commandObj = {
command: command,
args: args
}
// todo commented out because for some reasons server does not accept such a long
// array of many log lines. to examine later.
//
// add some useful debug info to examine weird stuff like this one
// UnprocessableError: Unable to encode a video with FPS near zero.
// todo consider removing this later or have it for debug=1 only?
//
// if (options.logger && options.logger.getLines) {
// commandObj.logLines = options.logger.getLines()
// }
writeStream(Buffer.from(JSON.stringify(commandObj)))
if (cb) {
// keep all callbacks async
setTimeout(function () {
cb()
}, 0)
}
}
}
function disconnect () {
if (connected) {
debug('Recorder: disconnect()')
if (userMedia) {
// prevents https://github.com/binarykitchen/videomail-client/issues/114
userMedia.unloadRemainingEventListeners()
}
if (submitting) {
// server will disconnect socket automatically after submitting
connecting = connected = false
} else if (stream) {
// force to disconnect socket right now to clean temp files on server
// event listeners will do the rest
stream.end()
stream = undefined
}
}
}
function cancelAnimationFrame () {
loop && loop.dispose()
}
function getIntervalSum () {
return loop.getElapsedTime()
}
function getAvgInterval () {
return (getIntervalSum() / framesCount)
}
this.getRecordingStats = function () {
return recordingStats
}
this.getAudioSampleRate = function () {
return userMedia.getAudioSampleRate()
}
this.stop = function (params) {
debug('stop()', params)
var limitReached = params.limitReached
this.emit(Events.STOPPING, limitReached)
loop.complete()
stopTime = Date.now()
recordingStats = {
avgFps: loop.getFPS(),
wantedFps: options.video.fps,
avgInterval: getAvgInterval(),
wantedInterval: 1e3 / options.video.fps,
intervalSum: getIntervalSum(),
framesCount: framesCount,
videoType: replay.getVideoType()
}
if (options.isAudioEnabled()) {
recordingStats.samplesCount = samplesCount
recordingStats.sampleRate = userMedia.getAudioSampleRate()
}
writeCommand('stop', recordingStats)
// beware, resetting will set framesCount to zero, so leave this here
this.reset()
}
this.back = function (cb) {
this.emit(Events.GOING_BACK)
show()
this.reset()
writeCommand('back', cb)
}
function reInitialiseAudio () {
debug('Recorder: reInitialiseAudio()')
clearUserMediaTimeout()
// important to free memory
userMedia && userMedia.stop()
userMediaLoaded = key = canvas = ctx = null
loadUserMedia()
}
this.unload = function (e) {
if (!unloaded) {
var cause
if (e) {
cause = e.name || e.statusText || e.toString()
}
debug('Recorder: unload()' + (cause ? ', cause: ' + cause : ''))
this.reset()
clearUserMediaTimeout()
disconnect()
unloaded = true
built = false
}
}
this.reset = function () {
// no need to reset when already unloaded
if (!unloaded) {
debug('Recorder: reset()')
this.emit(Events.RESETTING)
cancelAnimationFrame()
// important to free memory
userMedia && userMedia.stop()
replay.reset()
userMediaLoaded = key = canvas = ctx = waitingTime = null
}
}
this.validate = function () {
return connected && framesCount > 0 && canvas === null
}
this.isReady = function () {
return userMedia.isReady()
}
this.pause = function (params) {
var e = params && params.event
if (e instanceof window.Event) {
params.eventType = e.type
}
debug('pause()', params)
userMedia.pause()
loop.stop()
this.emit(Events.PAUSED)
sendPings()
}
this.isPaused = function () {
return userMedia && userMedia.isPaused()
}
this.resume = function () {
debug('Recorder: resume()')
stopPings()
this.emit(Events.RESUMING)
userMedia.resume()
loop.start()
}
function onFlushed (opts) {
var frameNumber = opts && opts.frameNumber
if (frameNumber === 1) {
self.emit(Events.FIRST_FRAME_SENT)
}
}
function createLoop () {
var newLoop = animitter({fps: options.video.fps}, draw)
// remember it first
originalAnimationFrameObject = newLoop.getRequestAnimationFrameObject()
return newLoop
}
function draw (deltaTime, elapsedTime) {
try {
// ctx and stream might become null while unloading
if (!self.isPaused() && stream && ctx) {
if (framesCount === 0) {
self.emit(Events.SENDING_FIRST_FRAME)
}
framesCount++
ctx.drawImage(
userMedia.getRawVisuals(),
0,
0,
canvas.width,
canvas.height
)
recordingBuffer = frame.toBuffer()
recordingBufferLength = recordingBuffer.length
if (recordingBufferLength < 1) {
throw VideomailError.create('Failed to extract webcam data.', options)
}
bytesSum += recordingBufferLength
writeStream(recordingBuffer, {
frameNumber: framesCount,
onFlushedCallback: onFlushed
})
// if (options.verbose) {
// debug(
// 'Frame #' + framesCount + ' (' + recordingBufferLength + ' bytes):',
// ' delta=' + deltaTime + 'ms, ' +
// ' elapsed=' + elapsedTime + 'ms'
// )
// }
visuals.checkTimer({intervalSum: elapsedTime})
}
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
this.record = function () {
if (unloaded) {
return false
}
// reconnect when needed
if (!connected) {
debug('Recorder: reconnecting before recording ...')
initSocket(function () {
self.once(Events.USER_MEDIA_READY, self.record)
})
return false
}
try {
canvas = userMedia.createCanvas()
} catch (exc) {
self.emit(
Events.ERROR,
VideomailError.create('Failed to create canvas.', exc, options)
)
return false
}
ctx = canvas.getContext('2d')
if (!canvas.width) {
self.emit(
Events.ERROR,
VideomailError.create('Canvas has an invalid width.', options)
)
return false
}
if (!canvas.height) {
self.emit(
Events.ERROR,
VideomailError.create('Canvas has an invalid height.', options)
)
return false
}
bytesSum = 0
frame = new Frame(canvas, options)
debug('Recorder: record()')
userMedia.record()
self.emit(Events.RECORDING, framesCount)
loop.start()
}
function setAnimationFrameObject (newObj) {
// must stop and then start to make it become effective, see
// https://github.com/hapticdata/animitter/issues/5#issuecomment-292019168
if (loop) {
var isRecording = self.isRecording()
loop.stop()
loop.setRequestAnimationFrameObject(newObj)
if (isRecording) {
loop.start()
}
}
}
function restoreAnimationFrameObject () {
debug('Recorder: restoreAnimationFrameObject()')
setAnimationFrameObject(originalAnimationFrameObject)
}
function loopWithTimeouts () {
debug('Recorder: loopWithTimeouts()')
const wantedInterval = 1e3 / options.video.fps
var processingTime = 0
var start
function raf (fn) {
return setTimeout(
function () {
start = Date.now()
fn()
processingTime = Date.now() - start
},
// reducing wanted interval by respecting the time it takes to
// compute internally since this is not multi-threaded like
// requestAnimationFrame
wantedInterval - processingTime
)
}
function cancel (id) {
clearTimeout(id)
}
setAnimationFrameObject({
requestAnimationFrame: raf,
cancelAnimationFrame: cancel
})
}
function buildElement () {
recorderElement = h('video.' + options.selectors.userMediaClass)
visuals.appendChild(recorderElement)
}
function correctDimensions () {
if (options.hasDefinedWidth()) {
recorderElement.width = self.getRecorderWidth(true)
}
if (options.hasDefinedHeight()) {
recorderElement.height = self.getRecorderHeight(true)
}
}
function initEvents () {
self
.on(Events.SUBMITTING, function () {
submitting = true
})
.on(Events.SUBMITTED, function () {
submitting = false
self.unload()
})
.on(Events.BLOCKING, function () {
blocking = true
clearUserMediaTimeout()
})
.on(Events.HIDE, function () {
self.hide()
})
.on(Events.LOADED_META_DATA, function () {
correctDimensions()
})
.on(Events.DISABLING_AUDIO, function () {
reInitialiseAudio()
})
.on(Events.ENABLING_AUDIO, function () {
reInitialiseAudio()
})
.on(Events.INVISIBLE, function () {
loopWithTimeouts()
})
.on(Events.VISIBLE, function () {
restoreAnimationFrameObject()
})
}
this.build = function () {
var err = browser.checkRecordingCapabilities()
if (!err) {
err = browser.checkBufferTypes()
}
if (err) {
this.emit(Events.ERROR, err)
} else {
recorderElement = visuals.querySelector('video.' + options.selectors.userMediaClass)
if (!recorderElement) {
buildElement()
}
correctDimensions()
// prevent audio feedback, see
// https://github.com/binarykitchen/videomail-client/issues/35
recorderElement.muted = true
if (!userMedia) {
userMedia = new UserMedia(this, options)
}
show()
if (!built) {
initEvents()
if (!connected) {
initSocket()
} else {
loadUserMedia()
}
} else {
loadUserMedia()
}
built = true
}
}
this.isPaused = function () {
return userMedia && userMedia.isPaused() && !loop.isRunning()
}
this.isRecording = function () {
// checking for stream.destroyed needed since
// https://github.com/binarykitchen/videomail.io/issues/296
return loop && loop.isRunning() && !this.isPaused() && !isNotifying() && stream && !stream.destroyed
}
this.hide = function () {
if (!isHidden()) {
recorderElement && hidden(recorderElement, true)
clearUserMediaTimeout()
clearRetryTimeout()
}
}
this.isUnloaded = function () {
return unloaded
}
// these two return the true dimensions of the webcam area.
// needed because on mobiles they might be different.
this.getRecorderWidth = function (responsive) {
if (userMedia) {
return userMedia.getRawWidth(responsive)
} else if (responsive && options.hasDefinedWidth()) {
return this.limitWidth(options.video.width)
}
}
this.getRecorderHeight = function (responsive) {
if (userMedia) {
return userMedia.getRawHeight(responsive)
} else if (responsive && options.hasDefinedHeight()) {
return this.calculateHeight(responsive)
}
}
function getRatio () {
var ratio
if (userMedia) {
ratio = userMedia.getVideoHeight() / userMedia.getVideoWidth()
} else {
ratio = options.getRatio()
}
return ratio
}
this.calculateWidth = function (responsive) {
var videoHeight
if (userMedia) {
videoHeight = userMedia.getVideoHeight()
} else if (recorderElement) {
videoHeight = recorderElement.videoHeight
}
return visuals.calculateWidth({
responsive: responsive,
ratio: getRatio(),
videoHeight: videoHeight
})
}
this.calculateHeight = function (responsive) {
var videoWidth
if (userMedia) {
videoWidth = userMedia.getVideoWidth()
} else if (recorderElement) {
videoWidth = recorderElement.videoWidth
}
return visuals.calculateHeight({
responsive: responsive,
ratio: getRatio(),
videoWidth: videoWidth
})
}
this.getRawVisualUserMedia = function () {
return recorderElement
}
this.isConnected = function () {
return connected
}
this.isConnecting = function () {
return connecting
}
this.limitWidth = function (width) {
return visuals.limitWidth(width)
}
this.limitHeight = function (height) {
return visuals.limitHeight(height)
}
this.isUserMediaLoaded = function () {
return userMediaLoaded
}
}
util.inherits(Recorder, EventEmitter)
module.exports = Recorder
}).call(this,require("buffer").Buffer)
},{"./../../constants":374,"./../../events":375,"./../../util/browser":380,"./../../util/eventEmitter":382,"./../../util/humanize":383,"./../../util/pretty":385,"./../../util/videomailError":387,"./userMedia":402,"animitter":1,"buffer":7,"canvas-to-buffer":8,"hidden":320,"hyperscript":322,"util":368,"websocket-stream":370}],401:[function(require,module,exports){
var util = require('util')
var h = require('hyperscript')
var hidden = require('hidden')
var Events = require('./../../events')
var Browser = require('./../../util/browser')
var EventEmitter = require('./../../util/eventEmitter')
var VideomailError = require('./../../util/videomailError')
var enableInlineVideo
if (typeof navigator !== 'undefined') {
enableInlineVideo = require('iphone-inline-video')
}
var Replay = function (parentElement, options) {
EventEmitter.call(this, options, 'Replay')
var self = this
var browser = new Browser(options)
var built,
replayElement,
videomail
function buildElement () {
replayElement = h('video.' + options.selectors.replayClass)
if (!replayElement.setAttribute) {
throw VideomailError.create('Please upgrade browser', options)
}
var err = browser.checkPlaybackCapabilities(replayElement)
if (err) {
throw err
} else {
parentElement.appendChild(replayElement)
}
}
function isStandalone () {
return parentElement.constructor.name === 'HTMLDivElement'
}
function copyAttributes (newVideomail) {
var attributeContainer
Object.keys(newVideomail).forEach(function (attribute) {
attributeContainer = parentElement.querySelector('.' + attribute)
if (attributeContainer) {
attributeContainer.innerHTML = newVideomail[attribute]
}
})
}
function correctDimensions (options) {
var width, height
if (videomail && videomail.playerWidth) {
width = videomail.playerWidth
} else if (parentElement.calculateWidth) {
width = parentElement.calculateWidth(options)
}
if (videomail && videomail.playerHeight) {
height = videomail.playerHeight
} else if (parentElement.calculateHeight) {
height = parentElement.calculateHeight(options)
}
if (width > 0) {
replayElement.style.width = width + 'px'
} else {
replayElement.style.width = 'auto'
}
if (height > 0) {
replayElement.style.height = height + 'px'
} else {
replayElement.style.height = 'auto'
}
}
this.setVideomail = function (newVideomail) {
videomail = newVideomail
if (videomail.webm) {
this.setWebMSource(videomail.webm)
}
if (videomail.mp4) {
this.setMp4Source(videomail.mp4)
}
if (videomail.poster) {
replayElement.setAttribute('poster', videomail.poster)
}
copyAttributes(videomail)
var hasAudio = videomail.recordingStats && videomail.recordingStats.sampleRate > 0
this.show(videomail.width, videomail.height, hasAudio)
}
this.show = function (recorderWidth, recorderHeight, hasAudio) {
correctDimensions({
responsive: true,
// beware that recorderWidth and recorderHeight can be null sometimes
videoWidth: recorderWidth || replayElement.videoWidth,
videoHeight: recorderHeight || replayElement.videoHeight
})
hidden(replayElement, false)
// parent element can be any object, be careful!
if (parentElement) {
if (parentElement.style) {
hidden(parentElement, false)
} else if (parentElement.show) {
parentElement.show()
}
}
if (hasAudio) {
// https://github.com/binarykitchen/videomail-client/issues/115
// do not set mute to false as this will mess up. just do not mention this attribute at all
replayElement.setAttribute('volume', 1)
} else if (!options.isAudioEnabled()) {
replayElement.setAttribute('muted', true)
}
// this must be called after setting the sources and when becoming visible
// see https://github.com/bfred-it/iphone-inline-video/issues/16
enableInlineVideo && enableInlineVideo(replayElement, {
iPad: true
})
// this forces to actually fetch the videos from the server
replayElement.load()
if (!videomail) {
self.emit(Events.PREVIEW_SHOWN)
} else {
self.emit(Events.REPLAY_SHOWN)
}
}
this.build = function () {
replayElement = parentElement.querySelector('video.' + options.selectors.replayClass)
if (!replayElement) {
buildElement()
}
this.hide()
replayElement.setAttribute('autoplay', true)
replayElement.setAttribute('autostart', true)
replayElement.setAttribute('autobuffer', true)
replayElement.setAttribute('playsinline', true)
replayElement.setAttribute('controls', 'controls')
replayElement.setAttribute('preload', 'auto')
replayElement.setAttribute('webkit-playsinline', 'webkit-playsinline')
if (!built) {
if (!isStandalone()) {
this.on(Events.PREVIEW, function (key, recorderWidth, recorderHeight) {
self.show(recorderWidth, recorderHeight)
})
}
replayElement.addEventListener('touchstart', function (e) {
e && e.preventDefault()
if (this.paused) {
play()
} else {
pause()
}
})
replayElement.onclick = function (e) {
e && e.preventDefault()
if (this.paused) {
play()
} else {
pause()
}
}
}
built = true
}
this.unload = function () {
built = false
}
this.getVideoSource = function (type) {
var sources = replayElement.getElementsByTagName('source')
var l = sources.length
var videoType = 'video/' + type
var source
if (l) {
var i
for (i = 0; i < l && !source; i++) {
if (sources[i].getAttribute('type') === videoType) {
source = sources[i]
}
}
}
return source
}
function setVideoSource (type, src, bustCache) {
var source = self.getVideoSource(type)
if (src && bustCache) {
src += '?' + Date.now()
}
if (!source) {
if (src) {
source = h('source', {
src: src,
type: 'video/' + type
})
replayElement.appendChild(source)
}
} else {
if (src) {
source.setAttribute('src', src)
} else {
replayElement.removeChild(source)
}
}
}
this.setMp4Source = function (src, bustCache) {
setVideoSource('mp4', src, bustCache)
}
this.setWebMSource = function (src, bustCache) {
setVideoSource('webm', src, bustCache)
}
this.getVideoType = function () {
return browser.getVideoType(replayElement)
}
function pause (cb) {
// avoids race condition, inspired by
// http://stackoverflow.com/questions/36803176/how-to-prevent-the-play-request-was-interrupted-by-a-call-to-pause-error
setTimeout(function () {
if (replayElement && replayElement.pause) {
replayElement.pause()
}
cb && cb()
}, 10)
}
function play () {
if (replayElement && replayElement.play) {
var p = replayElement.play()
if (p && (typeof Promise !== 'undefined') && (p instanceof Promise)) {
p.catch(function (reason) {
options.debug('Caught pending play exception: %s', reason)
})
}
}
}
this.reset = function (cb) {
// pause video to make sure it won't consume any memory
pause(function () {
if (replayElement) {
self.setMp4Source(null)
self.setWebMSource(null)
}
cb && cb()
})
}
this.hide = function () {
if (isStandalone()) {
hidden(parentElement, true)
} else {
replayElement && hidden(replayElement, true)
}
}
this.isShown = function () {
return replayElement && !hidden(replayElement)
}
this.getParentElement = function () {
return parentElement
}
}
util.inherits(Replay, EventEmitter)
module.exports = Replay
},{"./../../events":375,"./../../util/browser":380,"./../../util/eventEmitter":382,"./../../util/videomailError":387,"hidden":320,"hyperscript":322,"iphone-inline-video":328,"util":368}],402:[function(require,module,exports){
var h = require('hyperscript')
var AudioRecorder = require('./../../util/audioRecorder')
var VideomailError = require('./../../util/videomailError')
var EventEmitter = require('./../../util/eventEmitter')
var MEDIA_EVENTS = require('./../../util/mediaEvents')
var pretty = require('./../../util/pretty')
var Events = require('./../../events')
var EVENT_ASCII = '|—O—|'
module.exports = function (recorder, options) {
EventEmitter.call(this, options, 'UserMedia')
var rawVisualUserMedia = recorder && recorder.getRawVisualUserMedia()
var self = this
var paused = false
var record = false
var audioRecorder
var currentVisualStream
function attachMediaStream (stream) {
currentVisualStream = stream
if (typeof rawVisualUserMedia.srcObject !== 'undefined') {
rawVisualUserMedia.srcObject = stream
} else if (typeof rawVisualUserMedia.src !== 'undefined') {
var URL = window.URL || window.webkitURL
rawVisualUserMedia.src = URL.createObjectURL(stream) || stream
} else {
throw VideomailError.create(
'Error attaching stream to element.',
'Contact the developer about this',
options)
}
}
function setVisualStream (localMediaStream) {
if (localMediaStream) {
attachMediaStream(localMediaStream)
} else {
rawVisualUserMedia.removeAttribute('srcObject')
rawVisualUserMedia.removeAttribute('src')
currentVisualStream = null
}
}
function getVisualStream () {
if (rawVisualUserMedia.mozSrcObject) {
return rawVisualUserMedia.mozSrcObject
} else if (rawVisualUserMedia.srcObject) {
return rawVisualUserMedia.srcObject
} else {
return currentVisualStream
}
}
function hasEnded () {
if (rawVisualUserMedia.ended) {
return rawVisualUserMedia.ended
} else {
var visualStream = getVisualStream()
return visualStream && visualStream.ended
}
}
function hasInvalidDimensions () {
if ((rawVisualUserMedia.videoWidth && rawVisualUserMedia.videoWidth < 3) ||
(rawVisualUserMedia.height && rawVisualUserMedia.height < 3)) {
return true
}
}
function getTracks (localMediaStream) {
var tracks
if (localMediaStream && localMediaStream.getTracks) {
tracks = localMediaStream.getTracks()
}
return tracks
}
function getVideoTracks (localMediaStream) {
var videoTracks
if (localMediaStream && localMediaStream.getVideoTracks) {
videoTracks = localMediaStream.getVideoTracks()
}
return videoTracks
}
function getFirstVideoTrack (localMediaStream) {
var videoTracks = getVideoTracks(localMediaStream)
var videoTrack
if (videoTracks && videoTracks[0]) {
videoTrack = videoTracks[0]
}
return videoTrack
}
function logEvent (event, params) {
options.debug('UserMedia: ...', EVENT_ASCII, 'event', event, JSON.stringify(params))
}
function isPromise (anything) {
return (anything && (typeof Promise !== 'undefined') && (anything instanceof Promise))
}
function outputEvent (e) {
logEvent(e.type, {readyState: rawVisualUserMedia.readyState})
// remove myself
rawVisualUserMedia.removeEventListener &&
rawVisualUserMedia.removeEventListener(e.type, outputEvent)
}
this.unloadRemainingEventListeners = function () {
options.debug('UserMedia: unloadRemainingEventListeners()')
MEDIA_EVENTS.forEach(function (eventName) {
rawVisualUserMedia.removeEventListener(eventName, outputEvent)
})
}
this.init = function (localMediaStream, videoCallback, audioCallback, endedEarlyCallback) {
this.stop(localMediaStream, true)
var onPlayReached = false
var onLoadedMetaDataReached = false
var playingPromiseReached = false
if (options && options.isAudioEnabled()) {
audioRecorder = audioRecorder || new AudioRecorder(this, options)
}
function audioRecord () {
self.removeListener(Events.SENDING_FIRST_FRAME, audioRecord)
audioRecorder && audioRecorder.record(audioCallback)
}
function unloadAllEventListeners () {
options.debug('UserMedia: unloadAllEventListeners()')
self.removeListener(Events.SENDING_FIRST_FRAME, audioRecord)
rawVisualUserMedia.removeEventListener &&
rawVisualUserMedia.removeEventListener('play', onPlay)
rawVisualUserMedia.removeEventListener &&
rawVisualUserMedia.removeEventListener('loadedmetadata', onLoadedMetaData)
self.unloadRemainingEventListeners()
}
function play () {
// Resets the media element and restarts the media resource. Any pending events are discarded.
// But do them in the next tick to ensure event queue is ready for a lot to come
//
// this also to have the abort and emptied event to be processed as early as possible before
// all the other important events to come
setTimeout(function () {
try {
// todo debug and fix that weird error
// The play() request was interrupted by a new load request.
options.debug(
'UserMedia: play()',
'media.readyState=' + rawVisualUserMedia.readyState,
'media.paused=' + rawVisualUserMedia.paused,
'media.ended=' + rawVisualUserMedia.ended,
'media.played=' + pretty(rawVisualUserMedia.played)
)
rawVisualUserMedia.load()
var p = rawVisualUserMedia.play()
// using the promise here just experimental for now
// and this to catch any weird errors early if possible
if (isPromise(p)) {
p.then(function () {
if (!playingPromiseReached) {
options.debug('UserMedia: ... play promise successful. Playing now.')
playingPromiseReached = true
}
}).catch(function (reason) {
// promise can be interrupted, i.E. when switching tabs
// and promise can get resumed when switching back to tab, hence
// do not treat this like an error
options.debug('UserMedia:', reason.toString())
})
}
} catch (exc) {
unloadAllEventListeners()
endedEarlyCallback(exc)
}
}, 0)
}
function fireCallbacks () {
var readyState = rawVisualUserMedia.readyState
// ready state, see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
options.debug(
'UserMedia: fireCallbacks(' +
'readyState=' + readyState + ', ' +
'onPlayReached=' + onPlayReached + ', ' +
'onLoadedMetaDataReached=' + onLoadedMetaDataReached + ')'
)
if (onPlayReached && onLoadedMetaDataReached) {
videoCallback()
if (audioRecorder && audioCallback) {
try {
audioRecorder.init(localMediaStream)
self.on(Events.SENDING_FIRST_FRAME, audioRecord)
} catch (exc) {
unloadAllEventListeners()
endedEarlyCallback(exc)
}
}
}
}
function onPlay () {
try {
logEvent('play', {
readyState: rawVisualUserMedia.readyState,
audio: options.isAudioEnabled(),
width: rawVisualUserMedia.width,
height: rawVisualUserMedia.height,
videoWidth: rawVisualUserMedia.videoWidth,
videoHeight: rawVisualUserMedia.videoHeight
})
rawVisualUserMedia.removeEventListener &&
rawVisualUserMedia.removeEventListener('play', onPlay)
if (hasEnded() || hasInvalidDimensions()) {
endedEarlyCallback(
VideomailError.create(
'Already busy',
'Probably another browser window is using your webcam?',
options,
true
)
)
} else {
onPlayReached = true
fireCallbacks()
}
} catch (exc) {
unloadAllEventListeners()
endedEarlyCallback(exc)
}
}
// player modifications to perform that must wait until `loadedmetadata` has been triggered
function onLoadedMetaData () {
logEvent('loadedmetadata', {
readyState: rawVisualUserMedia.readyState,
width: rawVisualUserMedia.width,
height: rawVisualUserMedia.height,
videoWidth: rawVisualUserMedia.videoWidth,
videoHeight: rawVisualUserMedia.videoHeight
})
rawVisualUserMedia.removeEventListener &&
rawVisualUserMedia.removeEventListener('loadedmetadata', onLoadedMetaData)
if (!hasEnded() && !hasInvalidDimensions()) {
self.emit(Events.LOADED_META_DATA)
// for android devices, we cannot call play() unless meta data has been loaded!
play()
onLoadedMetaDataReached = true
fireCallbacks()
}
}
try {
var videoTrack = getFirstVideoTrack(localMediaStream)
if (!videoTrack) {
options.debug('UserMedia: detected (but no video tracks exist')
} else if (!videoTrack.enabled) {
throw VideomailError.create(
'Webcam is disabled',
'The video track seems to be disabled. Enable it in your system.',
options
)
} else {
var description
if (videoTrack.label && videoTrack.label.length > 0) {
description = videoTrack.label
}
description += ' with enabled=' + videoTrack.enabled
description += ', muted=' + videoTrack.muted
description += ', remote=' + videoTrack.remote
description += ', readyState=' + videoTrack.readyState
description += ', error=' + videoTrack.error
options.debug(
'UserMedia: ' + videoTrack.kind + ' detected.',
description || ''
)
}
// very useful i think, so leave this and just use options.debug()
var heavyDebugging = true
if (heavyDebugging) {
MEDIA_EVENTS.forEach(function (eventName) {
rawVisualUserMedia.addEventListener(eventName, outputEvent, false)
})
}
rawVisualUserMedia.addEventListener('loadedmetadata', onLoadedMetaData)
rawVisualUserMedia.addEventListener('play', onPlay)
// experimental, not sure if this is ever needed/called? since 2 apr 2017
// An error occurs while fetching the media data.
// Error can be an object with the code MEDIA_ERR_NETWORK or higher.
// networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted.
rawVisualUserMedia.addEventListener('error', function (err) {
self.emit(Events.ERROR, VideomailError.create(
'Weird webcam error',
// https://github.com/binarykitchen/videomail.io/issues/323
// tried just with err and JSON.stringify(err) but returns only "{}"
// adding more debug info just temporarily
//
// also i think should be ignored when fireCallbacks() was successful and it's
// playing fine anyway?
JSON.stringify(err) + ', ' +
JSON.stringify(arguments) + ', ' +
JSON.stringify(rawVisualUserMedia),
options
))
})
setVisualStream(localMediaStream)
play()
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
this.isReady = function () {
return !!rawVisualUserMedia.src
}
this.stop = function (visualStream, aboutToInitialize) {
try {
// do not stop "too much" when going to initialize anyway
if (!aboutToInitialize) {
if (!visualStream) {
visualStream = getVisualStream()
}
var tracks = getTracks(visualStream)
var newStopApiFound = false
if (tracks) {
tracks.forEach(function (track) {
if (track.stop) {
newStopApiFound = true
track.stop()
}
})
}
// will probably become obsolete in one year (after june 2017)
!newStopApiFound && visualStream && visualStream.stop && visualStream.stop()
setVisualStream(null)
audioRecorder && audioRecorder.stop()
audioRecorder = null
}
paused = record = false
} catch (exc) {
self.emit(Events.ERROR, exc)
}
}
this.createCanvas = function () {
return h('canvas', {
width: this.getRawWidth(true),
height: this.getRawHeight(true)
})
}
this.getVideoHeight = function () {
return rawVisualUserMedia.videoHeight
}
this.getVideoWidth = function () {
return rawVisualUserMedia.videoWidth
}
this.getRawWidth = function (responsive) {
var rawWidth = this.getVideoWidth()
var widthDefined = options.hasDefinedWidth()
if (widthDefined || options.hasDefinedHeight()) {
if (!responsive && widthDefined) {
rawWidth = options.video.width
} else {
rawWidth = recorder.calculateWidth(responsive)
}
}
if (responsive) {
rawWidth = recorder.limitWidth(rawWidth)
}
return rawWidth
}
this.getRawHeight = function (responsive) {
var rawHeight
if (options.hasDefinedDimension()) {
rawHeight = recorder.calculateHeight(responsive)
if (rawHeight < 1) {
throw VideomailError.create('Bad dimensions', 'Calculated raw height cannot be less than 1!', options)
}
} else {
rawHeight = this.getVideoHeight()
if (rawHeight < 1) {
throw VideomailError.create('Bad dimensions', 'Raw video height from DOM element cannot be less than 1!', options)
}
}
if (responsive) {
rawHeight = recorder.limitHeight(rawHeight)
}
return rawHeight
}
this.getRawVisuals = function () {
return rawVisualUserMedia
}
this.pause = function () {
paused = true
}
this.isPaused = function () {
return paused
}
this.resume = function () {
paused = false
}
this.record = function () {
record = true
}
this.isRecording = function () {
return record
}
this.getAudioSampleRate = function () {
if (audioRecorder) {
return audioRecorder.getSampleRate()
} else {
return -1
}
}
this.getCharacteristics = function () {
return {
audioSampleRate: this.getAudioSampleRate(),
muted: rawVisualUserMedia && rawVisualUserMedia.muted,
width: rawVisualUserMedia && rawVisualUserMedia.width,
height: rawVisualUserMedia && rawVisualUserMedia.height,
videoWidth: rawVisualUserMedia && rawVisualUserMedia.videoWidth,
videoHeight: rawVisualUserMedia && rawVisualUserMedia.videoHeight
}
}
}
},{"./../../events":375,"./../../util/audioRecorder":379,"./../../util/eventEmitter":382,"./../../util/mediaEvents":384,"./../../util/pretty":385,"./../../util/videomailError":387,"hyperscript":322}],"videomail-client":[function(require,module,exports){
var standardize = require('./util/standardize')
var Client = require('./client')
if (!navigator) {
throw new Error('Navigator is missing!')
} else {
// Ensures Videomail functionality is not broken on exotic browsers with shims.
//
// UMD (Universal Module Definition), inspired by https://github.com/es-shims/es5-shim
;(function (navigator) {
standardize(this, navigator)
}(navigator))
}
module.exports = Client
},{"./client":373,"./util/standardize":386}]},{},["videomail-client"]);
|
src/components/ContractCalculatorForm.js | ns6482/contractor-calculator | import React, {PropTypes} from 'react';
import Results from './Results';
import TextInput from './TextInput';
import {Toggle} from 'material-ui';
/**
* Todo expenses, mileage breakdown calculation
* disclaimer
* more written text
* fiverr design
*/
class ContractCalculatorForm extends React.Component {
constructor(props, context) {
super(props, context);
this.save = this.save.bind(this);
this.calculatorKeypress = this.calculatorKeypress.bind(this);
this.handleAdvancedToggle = this.handleAdvancedToggle.bind(this);
this.handleExpenseDetailToggle = this.handleExpenseDetailToggle.bind(this);
}
calculatorKeypress(name, value) {
this.props.calculate(this.props.contractorCalculator, name, value);
}
handleAdvancedToggle() {
this.props.toggleAdvanced(this.props.contractorCalculator);
}
handleExpenseDetailToggle() {
this.props.toggleExpenseDetail(this.props.contractorCalculator);
}
save() {
this.props.save(this.props.contractorCalculator);
}
render() {
const {contractorCalculator} = this.props;
return (
<div>
<h2>Take Home Pay Calculator</h2>
<TextInput floatingLabelText="Day Rate" onChange={this.calculatorKeypress} name="dayRate"
value={contractorCalculator.dayRate}/>
<br/>
<TextInput floatingLabelText="Working Weeks" onChange={this.calculatorKeypress} name="weeks"
value={contractorCalculator.weeks}/>
<br/>
<TextInput floatingLabelText="Wages (no NI to pay on 8040)" onChange={this.calculatorKeypress}
name="wages"
value={contractorCalculator.wages}/>
<br/>
<Toggle label="Expenses breakdown"
onToggle={this.handleExpenseDetailToggle}
toggled={contractorCalculator.expenseDetail}
/>
{contractorCalculator.expenseDetail ?
<div>
<TextInput floatingLabelText="Daily Mileage" onChange={this.calculatorKeypress}
name="mileage"
value={contractorCalculator.mileage}/>
<br/>
<TextInput floatingLabelText="Accountacy Fees (monthly)" onChange={this.calculatorKeypress}
name="accountancyFees"
value={contractorCalculator.accountancyFees}/>
<br/>
<TextInput floatingLabelText="Insurances" onChange={this.calculatorKeypress}
name="insurance"
value={contractorCalculator.insurance}/>
<br/>
<TextInput floatingLabelText="Other (monthly)" onChange={this.calculatorKeypress}
name="other"
value={contractorCalculator.other}/>
<br/>
</div>
: null}
<TextInput floatingLabelText="Expenses (annual)" onChange={this.calculatorKeypress} name="expenses"
disabled= {contractorCalculator.expenseDetail} value={contractorCalculator.expenses}/>
<br/>
<Toggle label="Show how dividend tax calculated"
onToggle={this.handleAdvancedToggle}
toggled={contractorCalculator.advanced}
/>
<hr/>
{contractorCalculator.necessaryDataIsProvidedToCalculateSavings &&
<Results advanced={contractorCalculator.advanced} results={contractorCalculator.results}/>}
</div>
);
}
}
ContractCalculatorForm.propTypes = {
save: PropTypes.func.isRequired,
calculate: PropTypes.func.isRequired,
toggleAdvanced: PropTypes.func.isRequired,
toggleExpenseDetail: PropTypes.func.isRequired,
contractorCalculator: PropTypes.object.isRequired
};
export default ContractCalculatorForm;
|
src/__tests__/MathJaxReact-test.js | kevinfrei/rollercoaster | import React from 'react';
import ReactDOM from 'react-dom';
import MathJaxReact from '../MathJaxReact';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<MathJaxReact formula='x^2+cos(x)'/>, div);
});
|
skeleton/public/js/jquery-1.9.1.min.js | veliamsli/revel | /*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;
return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l)
}b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window); |
js/jqwidgets/demos/react/app/treegrid/contextmenu/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxTreeGrid from '../../../jqwidgets-react/react_jqxtreegrid.js';
import JqxMenu from '../../../jqwidgets-react/react_jqxmenu.js';
class App extends React.Component {
componentDidMount() {
this.refs.myTreeGrid.expandRow(32);
this.refs.myTreeGrid.on('contextmenu', (event) => {
return false;
});
this.refs.myTreeGrid.on('rowClick', (event) => {
let args = event.args;
if (args.originalEvent.button == 2) {
let scrollTop = window.scrollX;
let scrollLeft = window.scrollY;
this.refs.myMenu.open(parseInt(event.args.originalEvent.clientX) + 5 + scrollLeft, parseInt(event.args.originalEvent.clientY) + 5 + scrollTop);
return false;
}
});
this.refs.myMenu.on('itemclick', (event) => {
let args = event.args;
let selection = this.refs.myTreeGrid.getSelection();
let rowid = selection[0].uid
if ($.trim($(args).text()) == "Edit Selected Row") {
this.refs.myTreeGrid.beginRowEdit(rowid);
} else {
this.refs.myTreeGrid.deleteRow(rowid);
}
});
}
render () {
// prepare the data
let source =
{
dataType: 'csv',
dataFields: [
{ name: 'EmployeeKey', type: 'number' },
{ name: 'ParentEmployeeKey', type: 'number' },
{ name: 'FirstName', type: 'string' },
{ name: 'LastName', type: 'string' },
{ name: 'Title', type: 'string' },
{ name: 'HireDate', type: 'date' },
{ name: 'BirthDate', type: 'date' },
{ name: 'Phone', type: 'string' },
{ name: 'Gender', type: 'string' },
{ name: 'DepartmentName', type: 'string' }
],
hierarchy:
{
keyDataField: { name: 'EmployeeKey' },
parentDataField: { name: 'ParentEmployeeKey' }
},
id: 'EmployeeKey',
url: '../sampledata/employeesadv.csv'
};
let dataAdapter = new $.jqx.dataAdapter(source);
// create Tree Grid
let columns = [
{ text: 'FirstName', dataField: 'FirstName', minWidth: 100, width: 200 },
{ text: 'LastName', dataField: 'LastName', width: 200 },
{ text: 'Department Name', dataField: 'DepartmentName', width: 200 },
{ text: 'Title', dataField: 'Title', width: 300 },
{ text: 'Birth Date', dataField: 'BirthDate', cellsFormat: 'd', width: 120 },
{ text: 'Hire Date', dataField: 'HireDate', cellsFormat: 'd', width: 120 },
{ text: 'Phone', dataField: 'Phone', cellsFormat: 'd', width: 120 }
];
return (
<div>
<JqxTreeGrid ref='myTreeGrid'
width={850}
source={dataAdapter}
columnsResize={true}
columns={columns}
/>
<JqxMenu ref='myMenu'
width={200} height={58}
autoOpenPopup={false} mode={'popup'}
>
<ul>
<li>Edit Selected Row</li>
<li>Delete Selected Row</li>
</ul>
</JqxMenu>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
ajax/libs/rxjs/2.2.24/rx.lite.js | laurenceHR/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
identity = Rx.helpers.identity = function (x) { return x; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) ||
'_es6shim_iterator_';
// Firefox ships a partial implementation using the name @@iterator.
// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
// So use that name if we detect it.
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var BooleanDisposable = (function () {
function BooleanDisposable (isSingle) {
this.isSingle = isSingle;
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
if (this.current && this.isSingle) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
inherits(SingleAssignmentDisposable, super_);
function SingleAssignmentDisposable() {
super_.call(this, true);
}
return SingleAssignmentDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
var SerialDisposable = Rx.SerialDisposable = (function (super_) {
inherits(SerialDisposable, super_);
function SerialDisposable() {
super_.call(this, false);
}
return SerialDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod = noop;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an iterable into an Observable sequence
*
* @example
* var res = Rx.Observable.fromIterable(new Map());
* var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence.
*/
Observable.fromIterable = function (iterable, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var iterator;
try {
iterator = iterable[$iterator$]();
} catch (e) {
observer.onError(e);
return;
}
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = iterator.next();
} catch (err) {
observer.onError(err);
return;
}
if (next.done) {
observer.onCompleted();
} else {
observer.onNext(next.value);
self();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == null) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throwException(new Error('Error'));
* var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
if (isPromise(xs)) { xs = observableFromPromise(xs); }
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) { observer.onCompleted(); }
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) { observer.onCompleted(); }
}));
return group;
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.doAction(observer);
* var res = observable.doAction(onNext);
* var res = observable.doAction(onNext, onError);
* var res = observable.doAction(onNext, onError, onCompleted);
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(42);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* var res = source.takeLast(5);
* var res = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function selectMany(selector) {
return this.select(function (x, i) {
var result = selector(x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.select(function (y) {
return resultSelector(x, y, i);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = immediateScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = immediateScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
function createListener (element, name, handler) {
// Node.js specific
if (element.addListener) {
element.addListener(name, handler);
return disposableCreate(function () {
element.removeListener(name, handler);
});
}
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (typeof el.item === 'function' && typeof el.length === 'number') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName); },
function (h) { Ember.removeListener(element, eventName); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
selector);
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
return function () {
if (promise && promise.abort) {
promise.abort();
}
}
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return !selector ?
this.multicast(new Subject()) :
this.multicast(function () {
return new Subject();
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.share();
*
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish(null).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return !selector ?
this.multicast(new AsyncSubject()) :
this.multicast(function () {
return new AsyncSubject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareValue(42);
*
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).
refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return !selector ?
this.multicast(new ReplaySubject(bufferSize, window, scheduler)) :
this.multicast(function () {
return new ReplaySubject(bufferSize, window, scheduler);
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
/** @private */
var ConnectableObservable = Rx.ConnectableObservable = (function (_super) {
inherits(ConnectableObservable, _super);
/**
* @constructor
* @private
*/
function ConnectableObservable(source, subject) {
var state = {
subject: subject,
source: source.asObservable(),
hasSubscription: false,
subscription: null
};
this.connect = function () {
if (!state.hasSubscription) {
state.hasSubscription = true;
state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () {
state.hasSubscription = false;
}));
}
return state.subscription;
};
function subscribe(observer) {
return state.subject.subscribe(observer);
}
_super.call(this, subscribe);
}
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.connect = function () { return this.connect(); };
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription = null, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect, subscription;
count++;
shouldConnect = count === 1;
subscription = source.subscribe(observer);
if (shouldConnect) {
connectableSubscription = source.connect();
}
return disposableCreate(function () {
subscription.dispose();
count--;
if (count === 0) {
connectableSubscription.dispose();
}
});
});
};
return ConnectableObservable;
}(Observable));
function observableTimerTimeSpan(dueTime, scheduler) {
var d = normalizeTime(dueTime);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(d, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
if (dueTime === period) {
return new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
});
}
return observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return observableTimerTimeSpanAndPeriod(period, period, scheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
*
* @example
* var res = Rx.Observable.timer(5000);
* var res = Rx.Observable.timer(5000, 1000);
* var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
scheduler || (scheduler = timeoutScheduler);
if (typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) {
scheduler = periodOrScheduler;
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* var res = Rx.Observable.delay(5000);
* var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.select(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return {
value: x,
interval: span
};
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.select(function (x) {
return {
value: x,
timestamp: scheduler.now()
};
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
if (atEnd) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
scheduler || (scheduler = timeoutScheduler);
if (typeof intervalOrSampler === 'number') {
return sampleObservable(this, observableinterval(intervalOrSampler, scheduler));
}
return sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
*
* @example
* 1 - res = source.timeout(new Date()); // As a date
* 2 - res = source.timeout(5000); // 5 seconds
* 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable
* 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable
* 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable
* 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
other || (other = observableThrow(new Error('Timeout')));
scheduler || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
var createTimer = function () {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
if (hasResult) {
observer.onNext(result);
}
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); });
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
*
* @example
* 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500));
* 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); });
* 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42));
*
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
var firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false, setTimer = function (timeout) {
var myId = id, timerWins = function () {
return id === myId;
};
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
d.dispose();
}, function (e) {
if (timerWins()) {
observer.onError(e);
}
}, function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
setTimer(firstTimeout);
var observerWins = function () {
var res = !switched;
if (res) {
id++;
}
return res;
};
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(timeout);
}
}, function (e) {
if (observerWins()) {
observer.onError(e);
}
}, function () {
if (observerWins()) {
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); });
*
* @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttleWithSelector = function (throttleDurationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
if (hasValue) {
observer.onNext(value);
}
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
*
* @example
* 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) {
return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); });
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
res.push(next.value);
}
}
observer.onNext(res);
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var t = scheduler.scheduleWithRelative(duration, function () {
observer.onCompleted();
});
return new CompositeDisposable(t, source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false,
t = scheduler.scheduleWithRelative(duration, function () { open = true; }),
d = source.subscribe(function (x) {
if (open) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
return new CompositeDisposable(t, d);
});
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [optional scheduler]);
* @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && observer.onNext(x); },
observer.onError.bind(observer),
observer.onCompleted.bind(observer)));
});
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]);
* 2 - res = source.takeUntilWithTime(5000, [optional scheduler]);
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} scheduler Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () {
observer.onCompleted();
}), source.subscribe(observer));
});
};
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.subject.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
var q = [], previous = true;
var subscription =
combineLatestSource(
this.source,
this.subject.distinctUntilChanged(),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (results.shouldFire && previous) {
observer.onNext(results.data);
}
if (results.shouldFire && !previous) {
while (q.length > 0) {
observer.onNext(q.shift());
}
previous = true;
} else if (!results.shouldFire && !previous) {
q.push(results.data);
} else if (!results.shouldFire && previous) {
previous = false;
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
this.subject.onNext(false);
return subscription;
}
function PausableBufferedObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (enableQueue == null) {
enableQueue = true;
}
_super.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
var published = this.publish().refCount();
return [
published.filter(predicate, thisArg),
published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
var AnonymousObservable = Rx.AnonymousObservable = (function (_super) {
inherits(AnonymousObservable, _super);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (typeof subscriber === 'undefined') {
subscriber = disposableEmpty;
} else if (typeof subscriber === 'function') {
subscriber = disposableCreate(subscriber);
}
return subscriber;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
_super.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, _super);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
_super.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (_super) {
function RemovableDisposable (subject, observer) {
this.subject = subject;
this.observer = observer;
};
RemovableDisposable.prototype.dispose = function () {
this.observer.dispose();
if (!this.subject.isDisposed) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
}
};
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = new RemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, _super);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
_super.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/* @private */
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
app/containers/App.js | sirgalleto/gearmanUI | // @flow
import React, { Component } from 'react';
import type { Children } from 'react';
export default class App extends Component {
props: {
children: Children
};
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
|
ajax/libs/yui/3.7.0/event-custom-base/event-custom-base-coverage.js | Teino1978-Corp/Teino1978-Corp-cdnjs | if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/event-custom-base/event-custom-base.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/event-custom-base/event-custom-base.js",
code: []
};
_yuitest_coverage["build/event-custom-base/event-custom-base.js"].code=["YUI.add('event-custom-base', function (Y, NAME) {","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," */","","Y.Env.evt = {"," handles: {},"," plugins: {}","};","","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * Allows for the insertion of methods that are executed before or after"," * a specified method"," * @class Do"," * @static"," */","","var DO_BEFORE = 0,"," DO_AFTER = 1,","","DO = {",""," /**"," * Cache of objects touched by the utility"," * @property objs"," * @static"," * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object "," * replaces the role of this property, but is considered to be private, and "," * is only mentioned to provide a migration path."," * "," * If you have a use case which warrants migration to the _yuiaop property, "," * please file a ticket to let us know what it's used for and we can see if "," * we need to expose hooks for that functionality more formally."," */"," objs: null,",""," /**"," * <p>Execute the supplied method before the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>"," * <dd>Replace the arguments that the original function will be"," * called with.</dd>"," * <dt></code>Y.Do.Prevent(message)</code></dt>"," * <dd>Don't execute the wrapped function. Other before phase"," * wrappers will be executed.</dd>"," * </dl>"," *"," * @method before"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {string} handle for the subscription"," * @static"," */"," before: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_BEFORE, f, obj, sFn);"," },",""," /**"," * <p>Execute the supplied method after the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>"," * <dd>Return <code>returnValue</code> instead of the wrapped"," * method's original return value. This can be further altered by"," * other after phase wrappers.</dd>"," * </dl>"," *"," * <p>The static properties <code>Y.Do.originalRetVal</code> and"," * <code>Y.Do.currentRetVal</code> will be populated for reference.</p>"," *"," * @method after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * @return {string} handle for the subscription"," * @static"," */"," after: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_AFTER, f, obj, sFn);"," },",""," /**"," * Execute the supplied method before or after the specified function."," * Used by <code>before</code> and <code>after</code>."," *"," * @method _inject"," * @param when {string} before or after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @return {string} handle for the subscription"," * @private"," * @static"," */"," _inject: function(when, fn, obj, sFn) {"," // object id"," var id = Y.stamp(obj), o, sid;",""," if (!obj._yuiaop) {"," // create a map entry for the obj if it doesn't exist, to hold overridden methods"," obj._yuiaop = {};"," }",""," o = obj._yuiaop;",""," if (!o[sFn]) {"," // create a map entry for the method if it doesn't exist"," o[sFn] = new Y.Do.Method(obj, sFn);",""," // re-route the method to our wrapper"," obj[sFn] = function() {"," return o[sFn].exec.apply(o[sFn], arguments);"," };"," }",""," // subscriber id"," sid = id + Y.stamp(fn) + sFn;",""," // register the callback"," o[sFn].register(sid, fn, when);",""," return new Y.EventHandle(o[sFn], sid);"," },",""," /**"," * Detach a before or after subscription."," *"," * @method detach"," * @param handle {string} the subscription handle"," * @static"," */"," detach: function(handle) {"," if (handle.detach) {"," handle.detach();"," }"," },",""," _unload: function(e, me) {"," }","};","","Y.Do = DO;","","//////////////////////////////////////////////////////////////////////////","","/**"," * Contains the return value from the wrapped method, accessible"," * by 'after' event listeners."," *"," * @property originalRetVal"," * @static"," * @since 3.2.0"," */","","/**"," * Contains the current state of the return value, consumable by"," * 'after' event listeners, and updated if an after subscriber"," * changes the return value generated by the wrapped function."," *"," * @property currentRetVal"," * @static"," * @since 3.2.0"," */","","//////////////////////////////////////////////////////////////////////////","","/**"," * Wrapper for a displaced method with aop enabled"," * @class Do.Method"," * @constructor"," * @param obj The object to operate on"," * @param sFn The name of the method to displace"," */","DO.Method = function(obj, sFn) {"," this.obj = obj;"," this.methodName = sFn;"," this.method = obj[sFn];"," this.before = {};"," this.after = {};","};","","/**"," * Register a aop subscriber"," * @method register"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype.register = function (sid, fn, when) {"," if (when) {"," this.after[sid] = fn;"," } else {"," this.before[sid] = fn;"," }","};","","/**"," * Unregister a aop subscriber"," * @method delete"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype._delete = function (sid) {"," 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 YArray = Y.Array,",""," AFTER = 'after',"," CONFIGS = ["," 'broadcast',"," 'monitored',"," 'bubbles',"," 'context',"," 'contextFn',"," 'currentTarget',"," 'defaultFn',"," 'defaultTargetOnly',"," 'details',"," 'emitFacade',"," 'fireOnce',"," 'async',"," 'host',"," 'preventable',"," 'preventedFn',"," 'queuable',"," 'silent',"," 'stoppedFn',"," 'target',"," 'type'"," ],",""," CONFIGS_HASH = YArray.hash(CONFIGS),",""," nativeSlice = Array.prototype.slice, ",""," YUI3_SIGNATURE = 9,"," YUI_LOG = 'yui:log',",""," mixConfigs = function(r, s, ov) {"," var p;",""," for (p in s) {"," if (CONFIGS_HASH[p] && (ov || !(p in r))) { "," r[p] = s[p];"," }"," }",""," return r;"," };","","/**"," * The CustomEvent class lets you define events for your application"," * that can be subscribed to by one or more independent component."," *"," * @param {String} type The type of event, which is passed to the callback"," * when the event fires."," * @param {object} o configuration object."," * @class CustomEvent"," * @constructor"," */","Y.CustomEvent = function(type, o) {",""," this._kds = Y.CustomEvent.keepDeprecatedSubs;",""," 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 {}"," * @deprecated"," */"," if (this._kds) {"," this.subscribers = {};"," }",""," /**"," * The subscribers to this event"," * @property _subscribers"," * @type Subscriber []"," * @private"," */"," this._subscribers = [];",""," /**"," * 'After' subscribers"," * @property afters"," * @type Subscriber {}"," */"," if (this._kds) {"," this.afters = {};"," }",""," /**"," * 'After' subscribers"," * @property _afters"," * @type Subscriber []"," * @private"," */"," 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);","","","};","","/**"," * Static flag to enable population of the <a href=\"#property_subscribers\">`subscribers`</a>"," * and <a href=\"#property_subscribers\">`afters`</a> properties held on a `CustomEvent` instance."," * "," * These properties were changed to private properties (`_subscribers` and `_afters`), and "," * converted from objects to arrays for performance reasons. "," *"," * Setting this property to true will populate the deprecated `subscribers` and `afters` "," * properties for people who may be using them (which is expected to be rare). There will"," * be a performance hit, compared to the new array based implementation."," *"," * If you are using these deprecated properties for a use case which the public API"," * does not support, please file an enhancement request, and we can provide an alternate "," * public implementation which doesn't have the performance cost required to maintiain the"," * properties as objects."," *"," * @property keepDeprecatedSubs"," * @static"," * @for CustomEvent"," * @type boolean"," * @default false"," * @deprecated"," */","Y.CustomEvent.keepDeprecatedSubs = false;","","Y.CustomEvent.mixConfigs = mixConfigs;","","Y.CustomEvent.prototype = {",""," constructor: Y.CustomEvent,",""," /**"," * 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._subscribers.length, a = this._afters.length, sib = this.sibling;",""," if (sib) {"," s += sib._subscribers.length;"," a += sib._afters.length;"," }",""," if (when) {"," return (when == 'after') ? a : s;"," }",""," return (s + a);"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('detach', 'attach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," this.monitored = true;"," var type = this.id + '|' + this.type + '_' + what,"," args = nativeSlice.call(arguments, 0);"," args[0] = type;"," return this.host.on.apply(this.host, args);"," },",""," /**"," * Get all of the subscribers to this event and any sibling event"," * @method getSubs"," * @return {Array} first item is the on subscribers, second the after."," */"," getSubs: function() {"," var s = this._subscribers, a = this._afters, sib = this.sibling;",""," s = (sib) ? s.concat(sib._subscribers) : s.concat();"," a = (sib) ? a.concat(sib._afters) : a.concat();",""," 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) {"," mixConfigs(this, o, force);"," },",""," /**"," * Create the Subscription for subscribing function, context, and bound"," * arguments. If this is a fireOnce event, the subscriber is immediately "," * notified."," *"," * @method _on"," * @param fn {Function} Subscription callback"," * @param [context] {Object} Override `this` in the callback"," * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()"," * @param [when] {String} \"after\" to slot into after subscribers"," * @return {EventHandle}"," * @protected"," */"," _on: function(fn, context, args, when) {","",""," 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.push(s);"," } else {"," this._subscribers.push(s);"," }",""," if (this._kds) {"," if (when == AFTER) {"," this.afters[s.id] = s;"," } else {"," this.subscribers[s.id] = s;"," }"," }",""," return new Y.EventHandle(this, s);"," },",""," /**"," * Listen for this event"," * @method subscribe"," * @param {Function} fn The function to execute."," * @return {EventHandle} Unsubscribe handle."," * @deprecated use on."," */"," subscribe: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, true);"," },"," "," /**"," * Listen for this event"," * @method on"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} An object with a detach method to detch the handler(s)."," */"," on: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;",""," if (this.monitored && this.host) {"," this.host._monitor('attach', this, {"," args: arguments"," });"," }"," return this._on(fn, context, a, true);"," },",""," /**"," * Listen for this event after the normal subscribers have been notified and"," * the default behavior has been applied. If a normal subscriber prevents the"," * default behavior, it also prevents after listeners from firing."," * @method after"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} handle Unsubscribe handle."," */"," after: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, AFTER);"," },",""," /**"," * Detach listeners."," * @method detach"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int} returns the number of subscribers unsubscribed."," */"," detach: function(fn, context) {"," // unsubscribe handle"," if (fn && fn.detach) {"," return fn.detach();"," }"," "," var i, s,"," found = 0,"," subs = this._subscribers,"," afters = this._afters;",""," for (i = subs.length; i >= 0; i--) {"," s = subs[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, subs, i);"," found++;"," }"," }",""," for (i = afters.length; i >= 0; i--) {"," s = afters[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, afters, i);"," found++;"," }"," }",""," return found;"," },",""," /**"," * Detach listeners."," * @method unsubscribe"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int|undefined} returns the number of subscribers unsubscribed."," * @deprecated use detach."," */"," unsubscribe: function() {"," return this.detach.apply(this, arguments);"," },",""," /**"," * Notify a single subscriber"," * @method _notify"," * @param {Subscriber} s the subscriber."," * @param {Array} args the arguments array to apply to the listener."," * @protected"," */"," _notify: function(s, args, ef) {","",""," var ret;",""," ret = s.notify(args, this);",""," if (false === ret || this.stopped > 1) {"," 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) {"," },",""," /**"," * 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) {"," return true;"," } else {",""," var args = nativeSlice.call(arguments, 0);",""," // this doesn't happen if the event isn't published"," // this.host._monitor('fire', this.type, args);",""," this.fired = true;",""," if (this.fireOnce) {"," this.firedWith = args;"," }",""," if (this.emitFacade) {"," return this.fireComplex(args);"," } else {"," return this.fireSimple(args);"," }"," }"," },",""," /**"," * Set up for notifying subscribers of non-emitFacade events."," *"," * @method fireSimple"," * @param args {Array} Arguments passed to fire()"," * @return Boolean false if a subscriber returned false"," * @protected"," */"," fireSimple: function(args) {"," this.stopped = 0;"," this.prevented = 0;"," if (this.hasSubs()) {"," var subs = this.getSubs();"," this._procSubs(subs[0], args);"," this._procSubs(subs[1], args);"," }"," 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, l;",""," for (i = 0, l = subs.length; i < l; i++) {"," s = subs[i];"," if (s && s.fn) {"," if (false === this._notify(s, args, ef)) {"," this.stopped = 2;"," }"," if (this.stopped == 2) {"," return false;"," }"," }"," }",""," return true;"," },",""," /**"," * Notifies the YUI instance if the event is configured with broadcast = 1,"," * and both the YUI instance and Y.Global if configured with broadcast = 2."," *"," * @method _broadcast"," * @param args {Array} Arguments sent to fire()"," * @private"," */"," _broadcast: function(args) {"," if (!this.stopped && this.broadcast) {",""," var a = args.concat();"," a.unshift(this.type);",""," if (this.host !== Y) {"," Y.fire.apply(Y, a);"," }",""," if (this.broadcast == 2) {"," Y.Global.fire.apply(Y.Global, a);"," }"," }"," },",""," /**"," * Removes all listeners"," * @method unsubscribeAll"," * @return {int} The number of listeners unsubscribed."," * @deprecated use detachAll."," */"," unsubscribeAll: function() {"," return this.detachAll.apply(this, arguments);"," },",""," /**"," * Removes all listeners"," * @method detachAll"," * @return {int} The number of listeners unsubscribed."," */"," detachAll: function() {"," return this.detach();"," },",""," /**"," * Deletes the subscriber from the internal store of on() and after()"," * subscribers."," *"," * @method _delete"," * @param s subscriber object."," * @param subs (optional) on or after subscriber array"," * @param index (optional) The index found."," * @private"," */"," _delete: function(s, subs, i) {"," var when = s._when;",""," if (!subs) {"," subs = (when === AFTER) ? this._afters : this._subscribers; "," i = YArray.indexOf(subs, s, 0);"," }",""," if (s && subs[i] === s) {"," subs.splice(i, 1);"," }",""," if (this._kds) {"," if (when === AFTER) {"," delete this.afters[s.id];"," } else {"," delete this.subscribers[s.id];"," }"," }",""," if (this.monitored && this.host) {"," this.host._monitor('detach', this, {"," ce: this,"," sub: s"," });"," }",""," if (s) {"," s.deleted = true;"," }"," }","};","/**"," * Stores the subscriber information to be used when the event fires."," * @param {Function} fn The wrapped function to execute."," * @param {Object} context The value of the keyword 'this' in the listener."," * @param {Array} args* 0..n additional arguments to supply the listener."," *"," * @class Subscriber"," * @constructor"," */","Y.Subscriber = function(fn, context, args, when) {",""," /**"," * The callback that will be execute when the event fires"," * This is wrapped by Y.rbind if obj was supplied."," * @property fn"," * @type Function"," */"," this.fn = fn;",""," /**"," * Optional 'this' keyword for the listener"," * @property context"," * @type Object"," */"," this.context = context;",""," /**"," * Unique subscriber id"," * @property id"," * @type String"," */"," this.id = Y.stamp(this);",""," /**"," * Additional arguments to propagate to the subscriber"," * @property args"," * @type Array"," */"," this.args = args;",""," this._when = when;",""," /**"," * Custom events for a given fire transaction."," * @property events"," * @type {EventTarget}"," */"," // this.events = null;",""," /**"," * This listener only reacts to the event once"," * @property once"," */"," // this.once = false;","","};","","Y.Subscriber.prototype = {"," constructor: Y.Subscriber,",""," _notify: function(c, args, ce) {"," if (this.deleted && !this.postponed) {"," if (this.postponed) {"," delete this.fn;"," delete this.context;"," } else {"," delete this.postponed;"," return null;"," }"," }"," var a = this.args, ret;"," switch (ce.signature) {"," case 0:"," ret = this.fn.call(c, ce.type, args, c);"," break;"," case 1:"," ret = this.fn.call(c, args[0] || null, c);"," break;"," default:"," if (a || args) {"," args = args || [];"," a = (a) ? args.concat(a) : args;"," ret = this.fn.apply(c, a);"," } else {"," ret = this.fn.call(c);"," }"," }",""," if (this.once) {"," ce._delete(this);"," }",""," return ret;"," },",""," /**"," * Executes the subscriber."," * @method notify"," * @param args {Array} Arguments array for the subscriber."," * @param ce {CustomEvent} The custom event that sent the notification."," */"," notify: function(args, ce) {"," var c = this.context,"," ret = true;",""," if (!c) {"," c = (ce.contextFn) ? ce.contextFn() : ce.context;"," }",""," // only catch errors if we will not re-throw them."," if (Y.config && Y.config.throwFail) {"," ret = this._notify(c, args, ce);"," } else {"," try {"," ret = this._notify(c, args, ce);"," } catch (e) {"," Y.error(this + ' failed: ' + e.message, e);"," }"," }",""," return ret;"," },",""," /**"," * Returns true if the fn and obj match this objects properties."," * Used by the unsubscribe method to match the right subscriber."," *"," * @method contains"," * @param {Function} fn the function to execute."," * @param {Object} context optional 'this' keyword for the listener."," * @return {boolean} true if the supplied arguments match this"," * subscriber's signature."," */"," contains: function(fn, context) {"," if (context) {"," return ((this.fn == fn) && this.context == context);"," } else {"," return (this.fn == fn);"," }"," },"," "," valueOf : function() {"," return this.id;"," }","","};","/**"," * Return value from all subscribe operations"," * @class EventHandle"," * @constructor"," * @param {CustomEvent} evt the custom event."," * @param {Subscriber} sub the subscriber."," */","Y.EventHandle = function(evt, sub) {",""," /**"," * The custom event"," *"," * @property evt"," * @type CustomEvent"," */"," this.evt = evt;",""," /**"," * The subscriber object"," *"," * @property sub"," * @type Subscriber"," */"," this.sub = sub;","};","","Y.EventHandle.prototype = {"," batch: function(f, c) {"," f.call(c || this, this);"," if (Y.Lang.isArray(this.evt)) {"," Y.Array.each(this.evt, function(h) {"," h.batch.call(c || h, f);"," });"," }"," },",""," /**"," * Detaches this subscriber"," * @method detach"," * @return {int} the number of detached listeners"," */"," detach: function() {"," var evt = this.evt, detached = 0, i;"," if (evt) {"," if (Y.Lang.isArray(evt)) {"," for (i = 0; i < evt.length; i++) {"," detached += evt[i].detach();"," }"," } else {"," evt._delete(this.sub);"," detached = 1;"," }",""," }",""," return detached;"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('attach', 'detach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," return this.evt.monitor.apply(this.evt, arguments);"," }","};","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * EventTarget provides the implementation for any object to"," * publish, subscribe and fire to custom events, and also"," * alows other EventTargets to target the object with events"," * sourced from the other object."," * EventTarget is designed to be used with Y.augment to wrap"," * EventCustom in an interface that allows events to be listened to"," * and fired by name. This makes it possible for implementing code to"," * subscribe to an event that either has not been created yet, or will"," * not be created at all."," * @class EventTarget"," * @param opts a configuration object"," * @config emitFacade {boolean} if true, all events will emit event"," * facade payloads by default (default false)"," * @config prefix {String} the prefix to apply to non-prefixed event names"," */","","var L = Y.Lang,"," PREFIX_DELIMITER = ':',"," CATEGORY_DELIMITER = '|',"," AFTER_PREFIX = '~AFTER~',"," WILD_TYPE_RE = /(.*?)(:)(.*?)/,",""," _wildType = Y.cached(function(type) {"," return type.replace(WILD_TYPE_RE, \"*$2$3\");"," }),",""," /**"," * If the instance has a prefix attribute and the"," * event type is not prefixed, the instance prefix is"," * applied to the supplied type."," * @method _getType"," * @private"," */"," _getType = Y.cached(function(type, pre) {",""," if (!pre || (typeof type !== \"string\") || 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 {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," once: function() {"," var handle = this.on.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Listen to a custom event hosted by this object one time."," * This is the equivalent to <code>after</code> except the"," * listener is immediatelly detached when it is executed."," * @method onceAfter"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," onceAfter: function() {"," var handle = this.after.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Takes the type parameter passed to 'on' and parses out the"," * various pieces that could be included in the type. If the"," * event type is passed without a prefix, it will be expanded"," * to include the prefix one is supplied or the event target"," * is configured with a default prefix."," * @method parseType"," * @param {String} type the type"," * @param {String} [pre=this._yuievt.config.prefix] the prefix"," * @since 3.3.0"," * @return {Array} an array containing:"," * * the detach category, if supplied,"," * * the prefixed event type,"," * * whether or not this is an after listener,"," * * the supplied event type"," */"," parseType: function(type, pre) {"," return _parseType(type, pre || this._yuievt.config.prefix);"," },",""," /**"," * Subscribe a callback function to a custom event fired by this object or"," * from an object that bubbles its events to this object."," *"," * Callback functions for events published with `emitFacade = true` will"," * receive an `EventFacade` as the first argument (typically named \"e\")."," * These callbacks can then call `e.preventDefault()` to disable the"," * behavior published to that event's `defaultFn`. See the `EventFacade`"," * API for all available properties and methods. Subscribers to"," * non-`emitFacade` events will receive the arguments passed to `fire()`"," * after the event name."," *"," * To subscribe to multiple events at once, pass an object as the first"," * argument, where the key:value pairs correspond to the eventName:callback,"," * or pass an array of event names as the first argument to subscribe to"," * all listed events with the same callback."," *"," * Returning `false` from a callback is supported as an alternative to"," * calling `e.preventDefault(); e.stopPropagation();`. However, it is"," * recommended to use the event methods whenever possible."," *"," * @method on"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," on: function(type, fn, context) {",""," var yuievt = this._yuievt,"," parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,"," detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,"," Node = Y.Node, n, domevent, isArr;",""," // full name, args, detachcategory, after"," this._monitor('attach', parts[1], {"," args: arguments,"," category: parts[0],"," after: parts[2]"," });",""," if (L.isObject(type)) {",""," if (L.isFunction(type)) {"," return Y.Do.before.apply(Y.Do, arguments);"," }",""," f = fn;"," c = context;"," args = nativeSlice.call(arguments, 0);"," ret = [];",""," if (L.isArray(type)) {"," isArr = true;"," }",""," after = type._after;"," delete type._after;",""," Y.each(type, function(v, k) {",""," if (L.isObject(v)) {"," f = v.fn || ((L.isFunction(v)) ? v : f);"," c = v.context || c;"," }",""," var nv = (after) ? AFTER_PREFIX : '';",""," args[0] = nv + ((isArr) ? v : k);"," args[1] = f;"," args[2] = c;",""," ret.push(this.on.apply(this, args));",""," }, this);",""," return (yuievt.chain) ? this : new Y.EventHandle(ret);"," }",""," detachcategory = parts[0];"," after = parts[2];"," shorttype = parts[3];",""," // extra redirection so we catch adaptor events too. take a look at this."," if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {"," args = nativeSlice.call(arguments, 0);"," args.splice(2, 0, Node.getDOMNode(this));"," return Y.on.apply(Y, args);"," }",""," type = parts[1];",""," if (Y.instanceOf(this, YUI)) {",""," adapt = Y.Env.evt.plugins[type];"," args = nativeSlice.call(arguments, 0);"," args[0] = shorttype;",""," if (Node) {"," n = args[2];",""," if (Y.instanceOf(n, Y.NodeList)) {"," n = Y.NodeList.getDOMNodes(n);"," } else if (Y.instanceOf(n, Node)) {"," n = Node.getDOMNode(n);"," }",""," domevent = (shorttype in Node.DOM_EVENTS);",""," // Captures both DOM events and event plugins."," if (domevent) {"," args[2] = n;"," }"," }",""," // check for the existance of an event adaptor"," if (adapt) {"," handle = adapt.on.apply(Y, args);"," } else if ((!type) || domevent) {"," handle = Y.Event._attach(args);"," }",""," }",""," if (!handle) {"," ce = yuievt.events[type] || this.publish(type);"," handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);"," }",""," if (detachcategory) {"," store[detachcategory] = store[detachcategory] || {};"," store[detachcategory][type] = store[detachcategory][type] || [];"," store[detachcategory][type].push(handle);"," }",""," return (yuievt.chain) ? this : handle;",""," },",""," /**"," * subscribe to an event"," * @method subscribe"," * @deprecated use on"," */"," subscribe: function() {"," return this.on.apply(this, arguments);"," },",""," /**"," * Detach one or more listeners the from the specified event"," * @method detach"," * @param type {string|Object} Either the handle to the subscriber or the"," * type of event. If the type"," * is not specified, it will attempt to remove"," * the listener from all hosted events."," * @param fn {Function} The subscribed function to unsubscribe, if not"," * supplied, all subscribers will be removed."," * @param context {Object} The custom object passed to subscribe. This is"," * optional, but if supplied will be used to"," * disambiguate multiple listeners that are the same"," * (e.g., you subscribe many object using a function"," * that lives on the prototype)"," * @return {EventTarget} the host"," */"," detach: function(type, fn, context) {"," var evts = this._yuievt.events, i,"," Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node));",""," // detachAll disabled on the Y instance."," if (!type && (this !== Y)) {"," for (i in evts) {"," if (evts.hasOwnProperty(i)) {"," evts[i].detach(fn, context);"," }"," }"," if (isNode) {"," Y.Event.purgeElement(Node.getDOMNode(this));"," }",""," return this;"," }",""," var parts = _parseType(type, this._yuievt.config.prefix),"," detachcategory = L.isArray(parts) ? parts[0] : null,"," shorttype = (parts) ? parts[3] : null,"," adapt, store = Y.Env.evt.handles, detachhost, cat, args,"," ce,",""," keyDetacher = function(lcat, ltype, host) {"," var handles = lcat[ltype], ce, i;"," if (handles) {"," for (i = handles.length - 1; i >= 0; --i) {"," ce = handles[i].evt;"," if (ce.host === host || ce.el === host) {"," handles[i].detach();"," }"," }"," }"," };",""," if (detachcategory) {",""," cat = store[detachcategory];"," type = parts[1];"," detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;",""," if (cat) {"," if (type) {"," keyDetacher(cat, type, detachhost);"," } else {"," for (i in cat) {"," if (cat.hasOwnProperty(i)) {"," keyDetacher(cat, i, detachhost);"," }"," }"," }",""," return this;"," }",""," // If this is an event handle, use it to detach"," } else if (L.isObject(type) && type.detach) {"," type.detach();"," return this;"," // extra redirection so we catch adaptor events too. take a look at this."," } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {"," args = nativeSlice.call(arguments, 0);"," args[2] = Node.getDOMNode(this);"," Y.detach.apply(Y, args);"," return this;"," }",""," adapt = Y.Env.evt.plugins[shorttype];",""," // The YUI instance handles DOM events and adaptors"," if (Y.instanceOf(this, YUI)) {"," args = nativeSlice.call(arguments, 0);"," // use the adaptor specific detach code if"," if (adapt && adapt.detach) {"," adapt.detach.apply(Y, args);"," return this;"," // DOM event fork"," } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {"," args[0] = type;"," Y.Event.detach.apply(Y.Event, args);"," return this;"," }"," }",""," // ce = evts[type];"," ce = evts[parts[1]];"," if (ce) {"," ce.detach(fn, context);"," }",""," return this;"," },",""," /**"," * detach a listener"," * @method unsubscribe"," * @deprecated use detach"," */"," unsubscribe: function() {"," 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;",""," if (L.isObject(type)) {"," ret = {};"," Y.each(type, function(v, k) {"," ret[k] = this.publish(k, v || opts);"," }, this);",""," return ret;"," }",""," type = (pre) ? _getType(type, pre) : type;",""," events = edata.events;"," ce = events[type];",""," this._monitor('publish', type, {"," args: arguments"," });",""," if (ce) {"," // ce.log(\"publish applying new config to published event: '\"+type+\"' exists\", 'info', 'event');"," if (opts) {"," ce.applyConfig(opts, true);"," }"," } else {"," // TODO: Lazy publish goes here."," defaults = edata.defaults;",""," // apply defaults"," ce = new Y.CustomEvent(type, defaults);"," if (opts) {"," ce.applyConfig(opts, true);"," }",""," 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 eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object."," * @param o {Object} Information about the event interaction, such as"," * fire() args, subscription category, publish config"," * @private"," */"," _monitor: function(what, eventType, o) {"," var monitorevt, ce, type;",""," if (eventType) {"," if (typeof eventType === \"string\") {"," type = eventType;"," ce = this.getEvent(eventType, true);"," } else {"," ce = eventType;"," type = eventType.type;"," }",""," if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {"," monitorevt = type + '_' + what;"," o.monitored = what;"," this.fire.call(this, monitorevt, o);"," }"," }"," },",""," /**"," * Fire a custom event by name. The callback functions will be executed"," * from the context specified when the event was created, and with the"," * following parameters."," *"," * If the custom event object hasn't been created, then the event hasn't"," * been published and it has no subscribers. For performance sake, we"," * immediate exit in this case. This means the event won't bubble, so"," * if the intention is that a bubble target be notified, the event must"," * be published on this object first."," *"," * The first argument is the event type, and any additional arguments are"," * passed to the listeners as parameters. If the first of these is an"," * object literal, and the event is configured to emit an event facade,"," * that object is mixed into the event facade and the facade is provided"," * in place of the original object."," *"," * @method fire"," * @param type {String|Object} The type of the event, or an object that contains"," * a 'type' property."," * @param arguments {Object*} an arbitrary set of parameters to pass to"," * the handler. If the first of these is an object literal and the event is"," * configured to emit an event facade, the event facade will replace that"," * parameter after the properties the object literal contains are copied to"," * the event facade."," * @return {EventTarget} the event host"," */"," fire: function(type) {",""," var typeIncluded = L.isString(type),"," t = (typeIncluded) ? type : (type && type.type),"," yuievt = this._yuievt,"," pre = yuievt.config.prefix, "," ce, ret, "," ce2,"," args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments;",""," t = (pre) ? _getType(t, pre) : t;",""," ce = this.getEvent(t, true);"," ce2 = this.getSibling(t, ce);",""," if (ce2 && !ce) {"," ce = this.publish(t);"," }",""," this._monitor('fire', (ce || t), {"," args: args"," });",""," // this event has not been published or subscribed to"," if (!ce) {"," if (yuievt.hasTargets) {"," return this.bubble({ type: t }, args, this);"," }",""," // otherwise there is nothing to be done"," ret = true;"," } else {"," ce.sibling = ce2;"," ret = ce.fire.apply(ce, args);"," }",""," return (yuievt.chain) ? this : ret;"," },",""," getSibling: function(type, ce) {"," var ce2;"," // delegate to *:type events if there are subscribers"," if (type.indexOf(PREFIX_DELIMITER) > -1) {"," type = _wildType(type);"," // 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 {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," after: function(type, fn) {",""," var a = nativeSlice.call(arguments, 0);",""," switch (L.type(type)) {"," case 'function':"," return Y.Do.after.apply(Y.Do, arguments);"," case 'array':"," // YArray.each(a[0], function(v) {"," // v = AFTER_PREFIX + v;"," // });"," // break;"," case 'object':"," a[0]._after = true;"," break;"," default:"," a[0] = AFTER_PREFIX + type;"," }",""," return this.on.apply(this, a);",""," },",""," /**"," * Executes the callback before a DOM event, custom event"," * or method. If the first argument is a function, it"," * is assumed the target is a method. For DOM and custom"," * events, this is an alias for Y.on."," *"," * For DOM and custom events:"," * type, callback, context, 0-n arguments"," *"," * For methods:"," * callback, object (method host), methodName, context, 0-n arguments"," *"," * @method before"," * @return detach handle"," */"," before: function() {"," return this.on.apply(this, arguments);"," }","","};","","Y.EventTarget = ET;","","// make Y an event target","Y.mix(Y, ET.prototype);","ET.call(Y, { bubbles: false });","","YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();","","/**"," * Hosts YUI page level events. This is where events bubble to"," * when the broadcast config is set to 2. This property is"," * only available if the custom event module is loaded."," * @property Global"," * @type EventTarget"," * @for YUI"," */","Y.Global = YUI.Env.globalEvents;","","// @TODO implement a global namespace function on Y.Global?","","/**","`Y.on()` can do many things:","","<ul>"," <li>Subscribe to custom events `publish`ed and `fire`d from Y</li>"," <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and"," `fire`d from any object in the YUI instance sandbox</li>"," <li>Subscribe to DOM events</li>"," <li>Subscribe to the execution of a method on any object, effectively"," treating that method as an event</li>","</ul>","","For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument.",""," Y.on('io:complete', function () {"," Y.MyApp.updateStatus('Transaction complete');"," });","","To subscribe to DOM events, pass the name of a DOM event as the first argument","and a CSS selector string as the third argument after the callback function.","Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,","array, or simply omitted (the default is the `window` object).",""," Y.on('click', function (e) {"," e.preventDefault();",""," // proceed with ajax form submission"," var url = this.get('action');"," ..."," }, '#my-form');","","The `this` object in DOM event callbacks will be the `Node` targeted by the CSS","selector or other identifier.","","`on()` subscribers for DOM events or custom events `publish`ed with a","`defaultFn` can prevent the default behavior with `e.preventDefault()` from the","event object passed as the first parameter to the subscription callback.","","To subscribe to the execution of an object method, pass arguments corresponding to the call signature for ","<a href=\"../classes/Do.html#methods_before\">`Y.Do.before(...)`</a>.","","NOTE: The formal parameter list below is for events, not for function","injection. See `Y.Do.before` for that signature.","","@method on","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@see Do.before","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `on()`, except that","the listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see on","@method once","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `once()`, except, like `after()`,","the subscription callback executes after all `on()` subscribers and the event's","`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase","subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`","subscribers will execute.","","The listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see once","@method onceAfter","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Like `on()`, this method creates a subscription to a custom event or to the","execution of a method on an object.","","For events, `after()` subscribers are executed after the event's","`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","NOTE: The subscription signature shown is for events, not for function","injection. See <a href=\"../classes/Do.html#methods_after\">`Y.Do.after`</a>","for that signature.","","@see on","@see Do.after","@method after","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [args*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","","}, '@VERSION@', {\"requires\": [\"oop\"]});"];
_yuitest_coverage["build/event-custom-base/event-custom-base.js"].lines = {"1":0,"9":0,"29":0,"76":0,"77":0,"78":0,"79":0,"82":0,"113":0,"114":0,"115":0,"116":0,"119":0,"138":0,"140":0,"142":0,"145":0,"147":0,"149":0,"152":0,"153":0,"158":0,"161":0,"163":0,"174":0,"175":0,"183":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"230":0,"231":0,"232":0,"234":0,"245":0,"246":0,"247":0,"264":0,"266":0,"273":0,"274":0,"275":0,"276":0,"277":0,"279":0,"281":0,"282":0,"284":0,"285":0,"293":0,"294":0,"297":0,"298":0,"301":0,"302":0,"303":0,"305":0,"306":0,"308":0,"309":0,"311":0,"316":0,"332":0,"333":0,"334":0,"346":0,"347":0,"348":0,"361":0,"362":0,"363":0,"374":0,"375":0,"388":0,"405":0,"439":0,"441":0,"442":0,"443":0,"447":0,"460":0,"462":0,"464":0,"466":0,"473":0,"481":0,"491":0,"509":0,"527":0,"528":0,"537":0,"544":0,"545":0,"554":0,"651":0,"663":0,"672":0,"689":0,"717":0,"719":0,"721":0,"733":0,"735":0,"736":0,"737":0,"740":0,"741":0,"744":0,"756":0,"757":0,"759":0,"760":0,"769":0,"771":0,"772":0,"774":0,"785":0,"804":0,"806":0,"807":0,"808":0,"810":0,"814":0,"815":0,"817":0,"820":0,"821":0,"822":0,"824":0,"828":0,"839":0,"840":0,"853":0,"855":0,"856":0,"860":0,"875":0,"876":0,"889":0,"890":0,"893":0,"898":0,"899":0,"900":0,"901":0,"902":0,"906":0,"907":0,"908":0,"909":0,"910":0,"914":0,"927":0,"940":0,"942":0,"944":0,"945":0,"948":0,"978":0,"979":0,"982":0,"987":0,"989":0,"990":0,"993":0,"994":0,"996":0,"1010":0,"1011":0,"1012":0,"1013":0,"1014":0,"1015":0,"1017":0,"1018":0,"1023":0,"1024":0,"1040":0,"1042":0,"1043":0,"1044":0,"1045":0,"1046":0,"1048":0,"1049":0,"1054":0,"1066":0,"1068":0,"1069":0,"1071":0,"1072":0,"1075":0,"1076":0,"1088":0,"1097":0,"1111":0,"1113":0,"1114":0,"1115":0,"1118":0,"1119":0,"1122":0,"1123":0,"1124":0,"1126":0,"1130":0,"1131":0,"1137":0,"1138":0,"1151":0,"1159":0,"1166":0,"1173":0,"1180":0,"1182":0,"1199":0,"1203":0,"1204":0,"1205":0,"1206":0,"1208":0,"1209":0,"1212":0,"1213":0,"1215":0,"1216":0,"1218":0,"1219":0,"1221":0,"1222":0,"1223":0,"1224":0,"1226":0,"1230":0,"1231":0,"1234":0,"1244":0,"1247":0,"1248":0,"1252":0,"1253":0,"1255":0,"1256":0,"1258":0,"1262":0,"1276":0,"1277":0,"1279":0,"1284":0,"1295":0,"1303":0,"1311":0,"1314":0,"1316":0,"1317":0,"1318":0,"1319":0,"1330":0,"1331":0,"1332":0,"1333":0,"1334":0,"1337":0,"1338":0,"1343":0,"1355":0,"1383":0,"1390":0,"1402":0,"1403":0,"1406":0,"1418":0,"1420":0,"1421":0,"1424":0,"1426":0,"1427":0,"1428":0,"1431":0,"1433":0,"1434":0,"1435":0,"1436":0,"1437":0,"1442":0,"1448":0,"1450":0,"1479":0,"1495":0,"1496":0,"1497":0,"1498":0,"1501":0,"1517":0,"1518":0,"1519":0,"1520":0,"1523":0,"1543":0,"1577":0,"1583":0,"1589":0,"1591":0,"1592":0,"1595":0,"1596":0,"1597":0,"1598":0,"1600":0,"1601":0,"1604":0,"1605":0,"1607":0,"1609":0,"1610":0,"1611":0,"1614":0,"1616":0,"1617":0,"1618":0,"1620":0,"1624":0,"1627":0,"1628":0,"1629":0,"1632":0,"1633":0,"1634":0,"1635":0,"1638":0,"1640":0,"1642":0,"1643":0,"1644":0,"1646":0,"1647":0,"1649":0,"1650":0,"1651":0,"1652":0,"1655":0,"1658":0,"1659":0,"1664":0,"1665":0,"1666":0,"1667":0,"1672":0,"1673":0,"1674":0,"1677":0,"1678":0,"1679":0,"1680":0,"1683":0,"1693":0,"1713":0,"1717":0,"1718":0,"1719":0,"1720":0,"1723":0,"1724":0,"1727":0,"1730":0,"1737":0,"1738":0,"1739":0,"1740":0,"1741":0,"1742":0,"1748":0,"1750":0,"1751":0,"1752":0,"1754":0,"1755":0,"1756":0,"1758":0,"1759":0,"1760":0,"1765":0,"1769":0,"1770":0,"1771":0,"1773":0,"1774":0,"1775":0,"1776":0,"1777":0,"1780":0,"1783":0,"1784":0,"1786":0,"1787":0,"1788":0,"1790":0,"1791":0,"1792":0,"1793":0,"1798":0,"1799":0,"1800":0,"1803":0,"1812":0,"1823":0,"1835":0,"1905":0,"1909":0,"1910":0,"1911":0,"1912":0,"1915":0,"1918":0,"1920":0,"1921":0,"1923":0,"1927":0,"1929":0,"1930":0,"1934":0,"1937":0,"1938":0,"1939":0,"1942":0,"1951":0,"1972":0,"1974":0,"1975":0,"1976":0,"1977":0,"1979":0,"1980":0,"1983":0,"1984":0,"1985":0,"1986":0,"2020":0,"2028":0,"2030":0,"2031":0,"2033":0,"2034":0,"2037":0,"2042":0,"2043":0,"2044":0,"2048":0,"2050":0,"2051":0,"2054":0,"2058":0,"2060":0,"2061":0,"2063":0,"2064":0,"2066":0,"2067":0,"2068":0,"2073":0,"2085":0,"2086":0,"2087":0,"2088":0,"2090":0,"2091":0,"2110":0,"2112":0,"2114":0,"2121":0,"2122":0,"2124":0,"2127":0,"2147":0,"2152":0,"2155":0,"2156":0,"2158":0,"2168":0};
_yuitest_coverage["build/event-custom-base/event-custom-base.js"].functions = {"before:75":0,"after:112":0,"]:152":0,"_inject:136":0,"detach:173":0,"Method:215":0,"register:230":0,"_delete:245":0,"exec:264":0,"AlterArgs:332":0,"AlterReturn:346":0,"Halt:361":0,"Prevent:374":0,"mixConfigs:438":0,"CustomEvent:460":0,"hasSubs:732":0,"monitor:755":0,"getSubs:768":0,"applyConfig:784":0,"_on:801":0,"subscribe:838":0,"on:852":0,"after:874":0,"detach:887":0,"unsubscribe:926":0,"_notify:937":0,"fire:977":0,"fireSimple:1009":0,"fireComplex:1022":0,"_procSubs:1039":0,"_broadcast:1065":0,"unsubscribeAll:1087":0,"detachAll:1096":0,"_delete:1110":0,"Subscriber:1151":0,"_notify:1202":0,"notify:1243":0,"contains:1275":0,"valueOf:1283":0,"EventHandle:1295":0,"(anonymous 2):1318":0,"batch:1315":0,"detach:1329":0,"monitor:1354":0,"(anonymous 3):1389":0,"(anonymous 4):1400":0,"(anonymous 5):1416":0,"ET:1445":0,"(anonymous 6):1496":0,"once:1494":0,"(anonymous 7):1518":0,"onceAfter:1516":0,"parseType:1542":0,"(anonymous 8):1607":0,"on:1575":0,"subscribe:1692":0,"keyDetacher:1736":0,"detach:1712":0,"unsubscribe:1811":0,"detachAll:1822":0,"unsubscribeAll:1834":0,"(anonymous 9):1911":0,"publish:1904":0,"_monitor:1971":0,"fire:2018":0,"getSibling:2057":0,"getEvent:2084":0,"after:2108":0,"before:2146":0,"(anonymous 1):1":0};
_yuitest_coverage["build/event-custom-base/event-custom-base.js"].coveredLines = 482;
_yuitest_coverage["build/event-custom-base/event-custom-base.js"].coveredFunctions = 70;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1);
YUI.add('event-custom-base', function (Y, NAME) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 1)", 1);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 9);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 29);
var DO_BEFORE = 0,
DO_AFTER = 1,
DO = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
* @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object
* replaces the role of this property, but is considered to be private, and
* is only mentioned to provide a migration path.
*
* If you have a use case which warrants migration to the _yuiaop property,
* please file a ticket to let us know what it's used for and we can see if
* we need to expose hooks for that functionality more formally.
*/
objs: null,
/**
* <p>Execute the supplied method before the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>
* <dd>Replace the arguments that the original function will be
* called with.</dd>
* <dt></code>Y.Do.Prevent(message)</code></dt>
* <dd>Don't execute the wrapped function. Other before phase
* wrappers will be executed.</dd>
* </dl>
*
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "before", 75);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 76);
var f = fn, a;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 77);
if (c) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 78);
a = [fn, c].concat(Y.Array(arguments, 4, true));
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 79);
f = Y.rbind.apply(Y, a);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 82);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "after", 112);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 113);
var f = fn, a;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 114);
if (c) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 115);
a = [fn, c].concat(Y.Array(arguments, 4, true));
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 116);
f = Y.rbind.apply(Y, a);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 119);
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
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_inject", 136);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 138);
var id = Y.stamp(obj), o, sid;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 140);
if (!obj._yuiaop) {
// create a map entry for the obj if it doesn't exist, to hold overridden methods
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 142);
obj._yuiaop = {};
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 145);
o = obj._yuiaop;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 147);
if (!o[sFn]) {
// create a map entry for the method if it doesn't exist
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 149);
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 152);
obj[sFn] = function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "]", 152);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 153);
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 158);
sid = id + Y.stamp(fn) + sFn;
// register the callback
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 161);
o[sFn].register(sid, fn, when);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 163);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 173);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 174);
if (handle.detach) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 175);
handle.detach();
}
},
_unload: function(e, me) {
}
};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 183);
Y.Do = DO;
//////////////////////////////////////////////////////////////////////////
/**
* Contains the return value from the wrapped method, accessible
* by 'after' event listeners.
*
* @property originalRetVal
* @static
* @since 3.2.0
*/
/**
* Contains the current state of the return value, consumable by
* 'after' event listeners, and updated if an after subscriber
* changes the return value generated by the wrapped function.
*
* @property currentRetVal
* @static
* @since 3.2.0
*/
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 215);
DO.Method = function(obj, sFn) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Method", 215);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 216);
this.obj = obj;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 217);
this.methodName = sFn;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 218);
this.method = obj[sFn];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 219);
this.before = {};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 220);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 230);
DO.Method.prototype.register = function (sid, fn, when) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "register", 230);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 231);
if (when) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 232);
this.after[sid] = fn;
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 234);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 245);
DO.Method.prototype._delete = function (sid) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_delete", 245);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 246);
delete this.before[sid];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 247);
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)
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 264);
DO.Method.prototype.exec = function () {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "exec", 264);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 266);
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 273);
for (i in bf) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 274);
if (bf.hasOwnProperty(i)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 275);
ret = bf[i].apply(this.obj, args);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 276);
if (ret) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 277);
switch (ret.constructor) {
case DO.Halt:
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 279);
return ret.retVal;
case DO.AlterArgs:
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 281);
args = ret.newArgs;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 282);
break;
case DO.Prevent:
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 284);
prevented = true;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 285);
break;
default:
}
}
}
}
// execute method
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 293);
if (!prevented) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 294);
ret = this.method.apply(this.obj, args);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 297);
DO.originalRetVal = ret;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 298);
DO.currentRetVal = ret;
// execute after methods.
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 301);
for (i in af) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 302);
if (af.hasOwnProperty(i)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 303);
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 305);
if (newRet && newRet.constructor == DO.Halt) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 306);
return newRet.retVal;
// Check for a new return value
} else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 308);
if (newRet && newRet.constructor == DO.AlterReturn) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 309);
ret = newRet.newRetVal;
// Update the static retval state
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 311);
DO.currentRetVal = ret;
}}
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 316);
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.
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 332);
DO.AlterArgs = function(msg, newArgs) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "AlterArgs", 332);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 333);
this.msg = msg;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 334);
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.
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 346);
DO.AlterReturn = function(msg, newRetVal) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "AlterReturn", 346);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 347);
this.msg = msg;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 348);
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.
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 361);
DO.Halt = function(msg, retVal) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Halt", 361);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 362);
this.msg = msg;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 363);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 374);
DO.Prevent = function(msg) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Prevent", 374);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 375);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 388);
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",
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 405);
var YArray = Y.Array,
AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
CONFIGS_HASH = YArray.hash(CONFIGS),
nativeSlice = Array.prototype.slice,
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log',
mixConfigs = function(r, s, ov) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "mixConfigs", 438);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 439);
var p;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 441);
for (p in s) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 442);
if (CONFIGS_HASH[p] && (ov || !(p in r))) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 443);
r[p] = s[p];
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 447);
return r;
};
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires.
* @param {object} o configuration object.
* @class CustomEvent
* @constructor
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 460);
Y.CustomEvent = function(type, o) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "CustomEvent", 460);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 462);
this._kds = Y.CustomEvent.keepDeprecatedSubs;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 464);
o = o || {};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 466);
this.id = Y.stamp(this);
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 473);
this.type = type;
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 481);
this.context = Y;
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
// this.monitored = false;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 491);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 509);
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 {}
* @deprecated
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 527);
if (this._kds) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 528);
this.subscribers = {};
}
/**
* The subscribers to this event
* @property _subscribers
* @type Subscriber []
* @private
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 537);
this._subscribers = [];
/**
* 'After' subscribers
* @property afters
* @type Subscriber {}
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 544);
if (this._kds) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 545);
this.afters = {};
}
/**
* 'After' subscribers
* @property _afters
* @type Subscriber []
* @private
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 554);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 651);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 663);
this.bubbles = true;
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 672);
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;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 689);
this.applyConfig(o, true);
};
/**
* Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a>
* and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance.
*
* These properties were changed to private properties (`_subscribers` and `_afters`), and
* converted from objects to arrays for performance reasons.
*
* Setting this property to true will populate the deprecated `subscribers` and `afters`
* properties for people who may be using them (which is expected to be rare). There will
* be a performance hit, compared to the new array based implementation.
*
* If you are using these deprecated properties for a use case which the public API
* does not support, please file an enhancement request, and we can provide an alternate
* public implementation which doesn't have the performance cost required to maintiain the
* properties as objects.
*
* @property keepDeprecatedSubs
* @static
* @for CustomEvent
* @type boolean
* @default false
* @deprecated
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 717);
Y.CustomEvent.keepDeprecatedSubs = false;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 719);
Y.CustomEvent.mixConfigs = mixConfigs;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 721);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "hasSubs", 732);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 733);
var s = this._subscribers.length, a = this._afters.length, sib = this.sibling;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 735);
if (sib) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 736);
s += sib._subscribers.length;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 737);
a += sib._afters.length;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 740);
if (when) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 741);
return (when == 'after') ? a : s;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 744);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "monitor", 755);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 756);
this.monitored = true;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 757);
var type = this.id + '|' + this.type + '_' + what,
args = nativeSlice.call(arguments, 0);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 759);
args[0] = type;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 760);
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() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "getSubs", 768);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 769);
var s = this._subscribers, a = this._afters, sib = this.sibling;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 771);
s = (sib) ? s.concat(sib._subscribers) : s.concat();
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 772);
a = (sib) ? a.concat(sib._afters) : a.concat();
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 774);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "applyConfig", 784);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 785);
mixConfigs(this, o, force);
},
/**
* Create the Subscription for subscribing function, context, and bound
* arguments. If this is a fireOnce event, the subscriber is immediately
* notified.
*
* @method _on
* @param fn {Function} Subscription callback
* @param [context] {Object} Override `this` in the callback
* @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()
* @param [when] {String} "after" to slot into after subscribers
* @return {EventHandle}
* @protected
*/
_on: function(fn, context, args, when) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_on", 801);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 804);
var s = new Y.Subscriber(fn, context, args, when);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 806);
if (this.fireOnce && this.fired) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 807);
if (this.async) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 808);
setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 810);
this._notify(s, this.firedWith);
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 814);
if (when == AFTER) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 815);
this._afters.push(s);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 817);
this._subscribers.push(s);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 820);
if (this._kds) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 821);
if (when == AFTER) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 822);
this.afters[s.id] = s;
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 824);
this.subscribers[s.id] = s;
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 828);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "subscribe", 838);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 839);
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 840);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "on", 852);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 853);
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 855);
if (this.monitored && this.host) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 856);
this.host._monitor('attach', this, {
args: arguments
});
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 860);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "after", 874);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 875);
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 876);
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
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 887);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 889);
if (fn && fn.detach) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 890);
return fn.detach();
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 893);
var i, s,
found = 0,
subs = this._subscribers,
afters = this._afters;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 898);
for (i = subs.length; i >= 0; i--) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 899);
s = subs[i];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 900);
if (s && (!fn || fn === s.fn)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 901);
this._delete(s, subs, i);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 902);
found++;
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 906);
for (i = afters.length; i >= 0; i--) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 907);
s = afters[i];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 908);
if (s && (!fn || fn === s.fn)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 909);
this._delete(s, afters, i);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 910);
found++;
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 914);
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() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribe", 926);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 927);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_notify", 937);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 940);
var ret;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 942);
ret = s.notify(args, this);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 944);
if (false === ret || this.stopped > 1) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 945);
return false;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 948);
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) {
},
/**
* 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() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fire", 977);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 978);
if (this.fireOnce && this.fired) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 979);
return true;
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 982);
var args = nativeSlice.call(arguments, 0);
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 987);
this.fired = true;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 989);
if (this.fireOnce) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 990);
this.firedWith = args;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 993);
if (this.emitFacade) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 994);
return this.fireComplex(args);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 996);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fireSimple", 1009);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1010);
this.stopped = 0;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1011);
this.prevented = 0;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1012);
if (this.hasSubs()) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1013);
var subs = this.getSubs();
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1014);
this._procSubs(subs[0], args);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1015);
this._procSubs(subs[1], args);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1017);
this._broadcast(args);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1018);
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fireComplex", 1022);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1023);
args[0] = args[0] || {};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1024);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_procSubs", 1039);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1040);
var s, i, l;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1042);
for (i = 0, l = subs.length; i < l; i++) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1043);
s = subs[i];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1044);
if (s && s.fn) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1045);
if (false === this._notify(s, args, ef)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1046);
this.stopped = 2;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1048);
if (this.stopped == 2) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1049);
return false;
}
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1054);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_broadcast", 1065);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1066);
if (!this.stopped && this.broadcast) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1068);
var a = args.concat();
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1069);
a.unshift(this.type);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1071);
if (this.host !== Y) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1072);
Y.fire.apply(Y, a);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1075);
if (this.broadcast == 2) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1076);
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {int} The number of listeners unsubscribed.
* @deprecated use detachAll.
*/
unsubscribeAll: function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribeAll", 1087);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1088);
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {int} The number of listeners unsubscribed.
*/
detachAll: function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detachAll", 1096);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1097);
return this.detach();
},
/**
* Deletes the subscriber from the internal store of on() and after()
* subscribers.
*
* @method _delete
* @param s subscriber object.
* @param subs (optional) on or after subscriber array
* @param index (optional) The index found.
* @private
*/
_delete: function(s, subs, i) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_delete", 1110);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1111);
var when = s._when;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1113);
if (!subs) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1114);
subs = (when === AFTER) ? this._afters : this._subscribers;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1115);
i = YArray.indexOf(subs, s, 0);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1118);
if (s && subs[i] === s) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1119);
subs.splice(i, 1);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1122);
if (this._kds) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1123);
if (when === AFTER) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1124);
delete this.afters[s.id];
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1126);
delete this.subscribers[s.id];
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1130);
if (this.monitored && this.host) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1131);
this.host._monitor('detach', this, {
ce: this,
sub: s
});
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1137);
if (s) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1138);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1151);
Y.Subscriber = function(fn, context, args, when) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Subscriber", 1151);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1159);
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1166);
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1173);
this.id = Y.stamp(this);
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1180);
this.args = args;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1182);
this._when = when;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1199);
Y.Subscriber.prototype = {
constructor: Y.Subscriber,
_notify: function(c, args, ce) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_notify", 1202);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1203);
if (this.deleted && !this.postponed) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1204);
if (this.postponed) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1205);
delete this.fn;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1206);
delete this.context;
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1208);
delete this.postponed;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1209);
return null;
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1212);
var a = this.args, ret;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1213);
switch (ce.signature) {
case 0:
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1215);
ret = this.fn.call(c, ce.type, args, c);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1216);
break;
case 1:
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1218);
ret = this.fn.call(c, args[0] || null, c);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1219);
break;
default:
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1221);
if (a || args) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1222);
args = args || [];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1223);
a = (a) ? args.concat(a) : args;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1224);
ret = this.fn.apply(c, a);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1226);
ret = this.fn.call(c);
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1230);
if (this.once) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1231);
ce._delete(this);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1234);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "notify", 1243);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1244);
var c = this.context,
ret = true;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1247);
if (!c) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1248);
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1252);
if (Y.config && Y.config.throwFail) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1253);
ret = this._notify(c, args, ce);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1255);
try {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1256);
ret = this._notify(c, args, ce);
} catch (e) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1258);
Y.error(this + ' failed: ' + e.message, e);
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1262);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "contains", 1275);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1276);
if (context) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1277);
return ((this.fn == fn) && this.context == context);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1279);
return (this.fn == fn);
}
},
valueOf : function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "valueOf", 1283);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1284);
return this.id;
}
};
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param {CustomEvent} evt the custom event.
* @param {Subscriber} sub the subscriber.
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1295);
Y.EventHandle = function(evt, sub) {
/**
* The custom event
*
* @property evt
* @type CustomEvent
*/
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "EventHandle", 1295);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1303);
this.evt = evt;
/**
* The subscriber object
*
* @property sub
* @type Subscriber
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1311);
this.sub = sub;
};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1314);
Y.EventHandle.prototype = {
batch: function(f, c) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "batch", 1315);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1316);
f.call(c || this, this);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1317);
if (Y.Lang.isArray(this.evt)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1318);
Y.Array.each(this.evt, function(h) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 2)", 1318);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1319);
h.batch.call(c || h, f);
});
}
},
/**
* Detaches this subscriber
* @method detach
* @return {int} the number of detached listeners
*/
detach: function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 1329);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1330);
var evt = this.evt, detached = 0, i;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1331);
if (evt) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1332);
if (Y.Lang.isArray(evt)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1333);
for (i = 0; i < evt.length; i++) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1334);
detached += evt[i].detach();
}
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1337);
evt._delete(this.sub);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1338);
detached = 1;
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1343);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "monitor", 1354);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1355);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1383);
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
WILD_TYPE_RE = /(.*?)(:)(.*?)/,
_wildType = Y.cached(function(type) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 3)", 1389);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1390);
return type.replace(WILD_TYPE_RE, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = Y.cached(function(type, pre) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 4)", 1400);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1402);
if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1403);
return type;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1406);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 5)", 1416);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1418);
var t = type, detachcategory, after, i;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1420);
if (!L.isString(t)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1421);
return t;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1424);
i = t.indexOf(AFTER_PREFIX);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1426);
if (i > -1) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1427);
after = true;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1428);
t = t.substr(AFTER_PREFIX.length);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1431);
i = t.indexOf(CATEGORY_DELIMITER);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1433);
if (i > -1) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1434);
detachcategory = t.substr(0, (i));
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1435);
t = t.substr(i+1);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1436);
if (t == '*') {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1437);
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1442);
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "ET", 1445);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1448);
var o = (L.isObject(opts)) ? opts : {};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1450);
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
}
};
};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1479);
ET.prototype = {
constructor: ET,
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>on</code> except the
* listener is immediatelly detached when it is executed.
* @method once
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
once: function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "once", 1494);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1495);
var handle = this.on.apply(this, arguments);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1496);
handle.batch(function(hand) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 6)", 1496);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1497);
if (hand.sub) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1498);
hand.sub.once = true;
}
});
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1501);
return handle;
},
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>after</code> except the
* listener is immediatelly detached when it is executed.
* @method onceAfter
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
onceAfter: function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "onceAfter", 1516);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1517);
var handle = this.after.apply(this, arguments);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1518);
handle.batch(function(hand) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 7)", 1518);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1519);
if (hand.sub) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1520);
hand.sub.once = true;
}
});
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1523);
return handle;
},
/**
* Takes the type parameter passed to 'on' and parses out the
* various pieces that could be included in the type. If the
* event type is passed without a prefix, it will be expanded
* to include the prefix one is supplied or the event target
* is configured with a default prefix.
* @method parseType
* @param {String} type the type
* @param {String} [pre=this._yuievt.config.prefix] the prefix
* @since 3.3.0
* @return {Array} an array containing:
* * the detach category, if supplied,
* * the prefixed event type,
* * whether or not this is an after listener,
* * the supplied event type
*/
parseType: function(type, pre) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "parseType", 1542);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1543);
return _parseType(type, pre || this._yuievt.config.prefix);
},
/**
* Subscribe a callback function to a custom event fired by this object or
* from an object that bubbles its events to this object.
*
* Callback functions for events published with `emitFacade = true` will
* receive an `EventFacade` as the first argument (typically named "e").
* These callbacks can then call `e.preventDefault()` to disable the
* behavior published to that event's `defaultFn`. See the `EventFacade`
* API for all available properties and methods. Subscribers to
* non-`emitFacade` events will receive the arguments passed to `fire()`
* after the event name.
*
* To subscribe to multiple events at once, pass an object as the first
* argument, where the key:value pairs correspond to the eventName:callback,
* or pass an array of event names as the first argument to subscribe to
* all listed events with the same callback.
*
* Returning `false` from a callback is supported as an alternative to
* calling `e.preventDefault(); e.stopPropagation();`. However, it is
* recommended to use the event methods whenever possible.
*
* @method on
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
on: function(type, fn, context) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "on", 1575);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1577);
var yuievt = this._yuievt,
parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1583);
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1589);
if (L.isObject(type)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1591);
if (L.isFunction(type)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1592);
return Y.Do.before.apply(Y.Do, arguments);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1595);
f = fn;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1596);
c = context;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1597);
args = nativeSlice.call(arguments, 0);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1598);
ret = [];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1600);
if (L.isArray(type)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1601);
isArr = true;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1604);
after = type._after;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1605);
delete type._after;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1607);
Y.each(type, function(v, k) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 8)", 1607);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1609);
if (L.isObject(v)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1610);
f = v.fn || ((L.isFunction(v)) ? v : f);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1611);
c = v.context || c;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1614);
var nv = (after) ? AFTER_PREFIX : '';
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1616);
args[0] = nv + ((isArr) ? v : k);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1617);
args[1] = f;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1618);
args[2] = c;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1620);
ret.push(this.on.apply(this, args));
}, this);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1624);
return (yuievt.chain) ? this : new Y.EventHandle(ret);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1627);
detachcategory = parts[0];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1628);
after = parts[2];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1629);
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1632);
if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1633);
args = nativeSlice.call(arguments, 0);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1634);
args.splice(2, 0, Node.getDOMNode(this));
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1635);
return Y.on.apply(Y, args);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1638);
type = parts[1];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1640);
if (Y.instanceOf(this, YUI)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1642);
adapt = Y.Env.evt.plugins[type];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1643);
args = nativeSlice.call(arguments, 0);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1644);
args[0] = shorttype;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1646);
if (Node) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1647);
n = args[2];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1649);
if (Y.instanceOf(n, Y.NodeList)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1650);
n = Y.NodeList.getDOMNodes(n);
} else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1651);
if (Y.instanceOf(n, Node)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1652);
n = Node.getDOMNode(n);
}}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1655);
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1658);
if (domevent) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1659);
args[2] = n;
}
}
// check for the existance of an event adaptor
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1664);
if (adapt) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1665);
handle = adapt.on.apply(Y, args);
} else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1666);
if ((!type) || domevent) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1667);
handle = Y.Event._attach(args);
}}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1672);
if (!handle) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1673);
ce = yuievt.events[type] || this.publish(type);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1674);
handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1677);
if (detachcategory) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1678);
store[detachcategory] = store[detachcategory] || {};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1679);
store[detachcategory][type] = store[detachcategory][type] || [];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1680);
store[detachcategory][type].push(handle);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1683);
return (yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "subscribe", 1692);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1693);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 1712);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1713);
var evts = this._yuievt.events, i,
Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node));
// detachAll disabled on the Y instance.
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1717);
if (!type && (this !== Y)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1718);
for (i in evts) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1719);
if (evts.hasOwnProperty(i)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1720);
evts[i].detach(fn, context);
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1723);
if (isNode) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1724);
Y.Event.purgeElement(Node.getDOMNode(this));
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1727);
return this;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1730);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "keyDetacher", 1736);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1737);
var handles = lcat[ltype], ce, i;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1738);
if (handles) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1739);
for (i = handles.length - 1; i >= 0; --i) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1740);
ce = handles[i].evt;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1741);
if (ce.host === host || ce.el === host) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1742);
handles[i].detach();
}
}
}
};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1748);
if (detachcategory) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1750);
cat = store[detachcategory];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1751);
type = parts[1];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1752);
detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1754);
if (cat) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1755);
if (type) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1756);
keyDetacher(cat, type, detachhost);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1758);
for (i in cat) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1759);
if (cat.hasOwnProperty(i)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1760);
keyDetacher(cat, i, detachhost);
}
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1765);
return this;
}
// If this is an event handle, use it to detach
} else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1769);
if (L.isObject(type) && type.detach) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1770);
type.detach();
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1771);
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1773);
if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1774);
args = nativeSlice.call(arguments, 0);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1775);
args[2] = Node.getDOMNode(this);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1776);
Y.detach.apply(Y, args);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1777);
return this;
}}}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1780);
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1783);
if (Y.instanceOf(this, YUI)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1784);
args = nativeSlice.call(arguments, 0);
// use the adaptor specific detach code if
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1786);
if (adapt && adapt.detach) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1787);
adapt.detach.apply(Y, args);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1788);
return this;
// DOM event fork
} else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1790);
if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1791);
args[0] = type;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1792);
Y.Event.detach.apply(Y.Event, args);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1793);
return this;
}}
}
// ce = evts[type];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1798);
ce = evts[parts[1]];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1799);
if (ce) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1800);
ce.detach(fn, context);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1803);
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribe", 1811);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1812);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detachAll", 1822);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1823);
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() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribeAll", 1834);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1835);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "publish", 1904);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1905);
var events, ce, ret, defaults,
edata = this._yuievt,
pre = edata.config.prefix;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1909);
if (L.isObject(type)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1910);
ret = {};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1911);
Y.each(type, function(v, k) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 9)", 1911);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1912);
ret[k] = this.publish(k, v || opts);
}, this);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1915);
return ret;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1918);
type = (pre) ? _getType(type, pre) : type;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1920);
events = edata.events;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1921);
ce = events[type];
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1923);
this._monitor('publish', type, {
args: arguments
});
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1927);
if (ce) {
// ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event');
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1929);
if (opts) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1930);
ce.applyConfig(opts, true);
}
} else {
// TODO: Lazy publish goes here.
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1934);
defaults = edata.defaults;
// apply defaults
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1937);
ce = new Y.CustomEvent(type, defaults);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1938);
if (opts) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1939);
ce.applyConfig(opts, true);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1942);
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;
// }
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1951);
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 eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object.
* @param o {Object} Information about the event interaction, such as
* fire() args, subscription category, publish config
* @private
*/
_monitor: function(what, eventType, o) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_monitor", 1971);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1972);
var monitorevt, ce, type;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1974);
if (eventType) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1975);
if (typeof eventType === "string") {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1976);
type = eventType;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1977);
ce = this.getEvent(eventType, true);
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1979);
ce = eventType;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1980);
type = eventType.type;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1983);
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1984);
monitorevt = type + '_' + what;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1985);
o.monitored = what;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1986);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fire", 2018);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2020);
var typeIncluded = L.isString(type),
t = (typeIncluded) ? type : (type && type.type),
yuievt = this._yuievt,
pre = yuievt.config.prefix,
ce, ret,
ce2,
args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2028);
t = (pre) ? _getType(t, pre) : t;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2030);
ce = this.getEvent(t, true);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2031);
ce2 = this.getSibling(t, ce);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2033);
if (ce2 && !ce) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2034);
ce = this.publish(t);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2037);
this._monitor('fire', (ce || t), {
args: args
});
// this event has not been published or subscribed to
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2042);
if (!ce) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2043);
if (yuievt.hasTargets) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2044);
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2048);
ret = true;
} else {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2050);
ce.sibling = ce2;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2051);
ret = ce.fire.apply(ce, args);
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2054);
return (yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "getSibling", 2057);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2058);
var ce2;
// delegate to *:type events if there are subscribers
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2060);
if (type.indexOf(PREFIX_DELIMITER) > -1) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2061);
type = _wildType(type);
// console.log(type);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2063);
ce2 = this.getEvent(type, true);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2064);
if (ce2) {
// console.log("GOT ONE: " + type);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2066);
ce2.applyConfig(ce);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2067);
ce2.bubbles = false;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2068);
ce2.broadcast = 0;
// ret = ce2.fire.apply(ce2, a);
}
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2073);
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) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "getEvent", 2084);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2085);
var pre, e;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2086);
if (!prefixed) {
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2087);
pre = this._yuievt.config.prefix;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2088);
type = (pre) ? _getType(type, pre) : type;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2090);
e = this._yuievt.events;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2091);
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
*
* @method after
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
after: function(type, fn) {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "after", 2108);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2110);
var a = nativeSlice.call(arguments, 0);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2112);
switch (L.type(type)) {
case 'function':
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2114);
return Y.Do.after.apply(Y.Do, arguments);
case 'array':
// YArray.each(a[0], function(v) {
// v = AFTER_PREFIX + v;
// });
// break;
case 'object':
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2121);
a[0]._after = true;
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2122);
break;
default:
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2124);
a[0] = AFTER_PREFIX + type;
}
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2127);
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() {
_yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "before", 2146);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2147);
return this.on.apply(this, arguments);
}
};
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2152);
Y.EventTarget = ET;
// make Y an event target
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2155);
Y.mix(Y, ET.prototype);
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2156);
ET.call(Y, { bubbles: false });
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2158);
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
*/
_yuitest_coverline("build/event-custom-base/event-custom-base.js", 2168);
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
/**
`Y.on()` can do many things:
<ul>
<li>Subscribe to custom events `publish`ed and `fire`d from Y</li>
<li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and
`fire`d from any object in the YUI instance sandbox</li>
<li>Subscribe to DOM events</li>
<li>Subscribe to the execution of a method on any object, effectively
treating that method as an event</li>
</ul>
For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument.
Y.on('io:complete', function () {
Y.MyApp.updateStatus('Transaction complete');
});
To subscribe to DOM events, pass the name of a DOM event as the first argument
and a CSS selector string as the third argument after the callback function.
Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,
array, or simply omitted (the default is the `window` object).
Y.on('click', function (e) {
e.preventDefault();
// proceed with ajax form submission
var url = this.get('action');
...
}, '#my-form');
The `this` object in DOM event callbacks will be the `Node` targeted by the CSS
selector or other identifier.
`on()` subscribers for DOM events or custom events `publish`ed with a
`defaultFn` can prevent the default behavior with `e.preventDefault()` from the
event object passed as the first parameter to the subscription callback.
To subscribe to the execution of an object method, pass arguments corresponding to the call signature for
<a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>.
NOTE: The formal parameter list below is for events, not for function
injection. See `Y.Do.before` for that signature.
@method on
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@see Do.before
@for YUI
**/
/**
Listen for an event one time. Equivalent to `on()`, except that
the listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see on
@method once
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Listen for an event one time. Equivalent to `once()`, except, like `after()`,
the subscription callback executes after all `on()` subscribers and the event's
`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase
subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`
subscribers will execute.
The listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see once
@method onceAfter
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Like `on()`, this method creates a subscription to a custom event or to the
execution of a method on an object.
For events, `after()` subscribers are executed after the event's
`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
NOTE: The subscription signature shown is for events, not for function
injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a>
for that signature.
@see on
@see Do.after
@method after
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [args*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
}, '@VERSION@', {"requires": ["oop"]});
|
packages/material-ui-icons/src/StayCurrentPortraitRounded.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="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" /></g></React.Fragment>
, 'StayCurrentPortraitRounded');
|
node_modules/react-icons/ti/weather-sunny.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const TiWeatherSunny = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m21.7 6.7l-1.7 4.9-1.7-4.9c-0.3-1 0.2-2 1.1-2.3 1-0.3 2 0.2 2.3 1.1 0.1 0.4 0.1 0.8 0 1.2z m-15 11.6l4.9 1.7-4.9 1.7c-1 0.3-2-0.2-2.3-1.1-0.3-1 0.2-2 1.1-2.3 0.4-0.1 0.8-0.1 1.2 0z m11.6 15l1.7-4.9 1.7 4.9c0.3 1-0.2 2-1.1 2.3-1 0.3-2-0.2-2.3-1.1-0.1-0.4-0.1-0.8 0-1.2z m15-11.6l-4.9-1.7 4.9-1.7c1-0.3 2 0.2 2.3 1.1 0.3 0.9-0.2 1.9-1.1 2.3-0.4 0.1-0.8 0.1-1.2 0z m-21.5-12.3l2.2 4.6-4.6-2.2c-0.9-0.5-1.2-1.5-0.8-2.4 0.4-0.9 1.5-1.2 2.3-0.8 0.4 0.2 0.7 0.5 0.9 0.8z m-2.4 18.8l4.6-2.2-2.2 4.6c-0.5 0.9-1.5 1.2-2.4 0.8-0.9-0.4-1.2-1.5-0.8-2.3 0.2-0.4 0.5-0.7 0.8-0.9z m18.8 2.4l-2.2-4.6 4.6 2.2c0.9 0.5 1.2 1.5 0.8 2.4-0.4 0.9-1.5 1.2-2.3 0.8-0.4-0.2-0.7-0.5-0.9-0.8z m2.4-18.9l-4.6 2.3 2.2-4.6c0.5-0.9 1.5-1.2 2.4-0.8 0.9 0.4 1.2 1.5 0.8 2.3-0.2 0.4-0.5 0.7-0.8 0.8z m-10.6 15.8c-4.1 0-7.5-3.4-7.5-7.5s3.4-7.5 7.5-7.5 7.5 3.4 7.5 7.5-3.4 7.5-7.5 7.5z m0-11.7c-2.3 0-4.2 1.9-4.2 4.2s1.9 4.2 4.2 4.2 4.2-1.9 4.2-4.2-1.9-4.2-4.2-4.2z"/></g>
</Icon>
)
export default TiWeatherSunny
|
src/components/MultiSelect/MultiSelect-story.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import {
withKnobs,
boolean,
select,
text,
object,
} from '@storybook/addon-knobs';
import { withReadme } from 'storybook-readme';
import readme from './README.md';
import MultiSelect from '../MultiSelect';
const items = [
{
id: 'downshift-1-item-0',
text: 'Option 1',
},
{
id: 'downshift-1-item-1',
text: 'Option 2',
},
{
id: 'downshift-1-item-2',
text: 'Option 3',
},
{
id: 'downshift-1-item-3',
text: 'Option 4',
},
{
id: 'downshift-1-item-4',
text:
'An example option that is really long to show what should be done to handle long text',
},
];
const defaultLabel = 'MultiSelect Label';
const defaultPlaceholder = 'Filter';
const types = {
'Default (default)': 'default',
'Inline (inline)': 'inline',
};
const props = () => ({
id: text('MultiSelect ID (id)', 'carbon-multiselect-example'),
titleText: text('Title (titleText)', 'Multiselect title'),
helperText: text('Helper text (helperText)', 'This is not helper text'),
filterable: boolean(
'Filterable (`<MultiSelect.Filterable>` instead of `<MultiSelect>`)',
false
),
disabled: boolean('Disabled (disabled)', false),
light: boolean('Light variant (light)', false),
useTitleInItem: boolean('Show tooltip on hover', false),
type: select('UI type (Only for `<MultiSelect>`) (type)', types, 'default'),
label: text('Label (label)', defaultLabel),
invalid: boolean('Show form validation UI (invalid)', false),
invalidText: text(
'Form validation UI content (invalidText)',
'Invalid Selection'
),
onChange: action('onChange'),
listBoxMenuIconTranslationIds: object(
'Listbox menu icon translation IDs (for translateWithId callback)',
{
'close.menu': 'Close menu',
'open.menu': 'Open menu',
}
),
selectionFeedback: select(
'Selection feedback',
['top', 'fixed', 'top-after-reopen'],
'top-after-reopen'
),
});
storiesOf('MultiSelect', module)
.addDecorator(withKnobs)
.add(
'default',
withReadme(readme, () => {
const {
filterable,
listBoxMenuIconTranslationIds,
selectionFeedback,
...multiSelectProps
} = props();
const ComponentToUse = !filterable ? MultiSelect : MultiSelect.Filterable;
const placeholder = !filterable ? undefined : defaultPlaceholder;
return (
<div style={{ width: 300 }}>
<ComponentToUse
{...multiSelectProps}
items={items}
itemToString={item => (item ? item.text : '')}
placeholder={placeholder}
translateWithId={id => listBoxMenuIconTranslationIds[id]}
selectionFeedback={selectionFeedback}
/>
</div>
);
}),
{
info: {
text: `
MultiSelect
`,
},
}
)
.add(
'with initial selected items',
withReadme(readme, () => {
const {
filterable,
listBoxMenuIconTranslationIds,
selectionFeedback,
...multiSelectProps
} = props();
const ComponentToUse = !filterable ? MultiSelect : MultiSelect.Filterable;
const placeholder = !filterable ? undefined : defaultPlaceholder;
return (
<div style={{ width: 300 }}>
<ComponentToUse
{...multiSelectProps}
items={items}
itemToString={item => (item ? item.text : '')}
initialSelectedItems={[items[0], items[1]]}
placeholder={placeholder}
translateWithId={id => listBoxMenuIconTranslationIds[id]}
selectionFeedback={selectionFeedback}
/>
</div>
);
}),
{
info: {
text: `
Provide a set of items to initially select in the control
`,
},
}
);
|
webapp/src/app/App.js | cpollet/itinerants | import React from 'react';
import MenuContainer from './menu/containers/MenuContainer';
import InfoStaleState from './availability/containers/InfoStaleState';
import AlertSyncFail from './availability/containers/AlertSyncFail';
import styles from './App.less';
import Alert from '../widgets/Alert';
class App extends React.Component {
render() {
return (
<div className={styles.component}>
<h1>Itinérants</h1>
{this.props.fetchError && <Alert type="error">Une erreur est survenue, réessaie plus tard</Alert>}
<div className={styles.container}>
<div className={styles.menuContainer}>
<MenuContainer location={this.props.location}/>
</div>
<div className={styles.contentContainer}>
<InfoStaleState text="Sauvegarde en cours..."/>
<AlertSyncFail title="Erreur" text="impossible de sauvegarder"/>
{this.props.children}
</div>
</div>
</div>
);
}
}
App.propTypes = {
children: React.PropTypes.node,
location: React.PropTypes.object,
fetchError: React.PropTypes.bool.isRequired,
};
App.defaultProps = {
fetchError: false,
};
export default App;
|
ozwillo-datacore-web/src/main/webapp/dc-ui/src/components/reading/serverConfiguration.js | ozwillo/ozwillo-datacore | import React from 'react';
import LinkPlayground from '../linkPlayground.js';
export default class serverConfiguration extends React.Component{
render() {
return (
<div className="center">
<h2>Server Configuration</h2>
<div className="ui segment">
<p>
## Development mode (also allows to set system property datacore.dropdb=true ex. in maven)<br/>
datacore.devmode=true<br/>
## Shard Endpoint - full URL (for clients...)<br/>
datacoreApiServer.baseUrl=https://data.ozwillo-preprod.eu<br/><br/>
## Container - default URL (for URIs...)<br/>
datacoreApiServer.containerUrl=http://data.ozwillo.com<br/>
## Other (or all) known Datacores (comma-separated container URLs)<br/>
datacoreApiServer.knownDatacoreContainerUrls=<br/><br/>
## Query :<br/>
## default maximum number of documents to scan when fulfilling a query, overriden by<br/>
## DCFields', themselves limited by DCModel's. 0 means no limit (for tests), else ex.<br/><br/>
## 1000 (secure default), 100000 (on query-only nodes using secondary & timeout)...<br/>
## http://docs.mongodb.org/manual/reference/operator/meta/maxScan/<br/>
datacoreApiServer.query.maxScan=0<br/>
## default maximum start position<br/>
datacoreApiServer.query.maxStart=500<br/>
## default maximum number of documents returned<br/>
datacoreApiServer.query.maxLimit=100<br/>
## default number of documents returned<br/>
datacoreApiServer.query.defaultLimit=10<br/><br/>
## Kernel Configuration<br/>
kernel.baseUrl=https://kernel.ozwillo-preprod.eu<br/>
</p>
</div>
</div>
);
}
}
|
src/components/Menu.js | angeloocana/angeloocana | import React from 'react';
import PropTypes from 'prop-types';
import MenuIcon from 'react-icons/lib/fa/bars';
import { InvisibleSpan } from './Invisible';
import styled from 'styled-components';
import Link from 'gatsby-link';
import { endsWith } from 'ramda';
import { injectIntl, FormattedMessage } from 'react-intl';
const CloseNav = styled.section`
${props => props.isOpen
? ` top: 0;
left: 0;
right: 0;
bottom: 0;
position: fixed;`
: ''};
`;
const Nav = styled.nav`
text-align: center;
position: fixed;
top: 0;
right: calc(2rem - 100%);
width: 100%;
z-index: 2;
padding: ${props => props.theme.menu.padding};
transition-timing-function: ease-in, step-start, cubic-bezier(0.1, 0.7, 1.0, 0.1);
${props => props.isOpen
? `height: 100%;`
: `height: 4rem;`};
transition: ${props => props.isOpen
? 'transform 1s, background-color 0.5s'
: 'transform 0.5s, background-color 1s'};
background-color: ${props => props.isOpen
? props.theme.menu.opened.bg
: props.theme.menu.closed.bg};
${props => props.isOpen
? 'transform: translateX(-60%);'
: ''};
@media (min-width: ${props => props.theme.maxWidth}) {
right: calc(-50% + -29rem);
}
`;
const MenuLabel = styled.label`
width: ${props => props.theme.menu.label.width};
height: ${props => props.theme.menu.label.height};
position: relative;
float: left;
cursor: pointer;
font-size: ${props => props.theme.menu.label.fontSize};
transition: transform 0.6s, rotate 0.4s;
transition-timing-function: ease-in, step-start, cubic-bezier(0.1, 0.7, 1.0, 0.1);
&:hover {
transform: scale(1.1) rotate(180deg);
transition: transform 0.6s, rotate 0.4s;
transition-timing-function: ease-in, step-start, cubic-bezier(0.1, 0.7, 1.0, 0.1);
}
`;
const Checkbox = styled.input`
position: absolute;
opacity: 0.02;
cursor: pointer;
top: 0;
right: 0;
width: 100%;
height: 100%;
`;
const MenuLink = styled(Link)`
font-size: ${props => props.theme.menu.a.fontSize};
padding-bottom: ${props => props.theme.menu.a.paddingBottom};
display: block;
text-align: ${props => props.theme.menu.a.textAlign};
text-decoration: none;
transition: 0.5s;
color: ${props => props.selected
? props.theme.menu.a.active.color
: props.theme.menu.a.color};
&:hover {
color: ${props => props.theme.menu.a.active.color};
transition: 0.5s;
}
`;
const MenuA = MenuLink.withComponent(styled.a``);
const Ul = styled.ul`
display: block;
margin-top: ${props => props.theme.menu.ul.marginTop};
margin-left: ${props => props.theme.menu.ul.marginLeft};
list-style: none;
transition: opacity 1s, transform 0.5s;
transform: ${props => props.isOpen ? 'translateX(-4rem)' : ''};
opacity: ${props => props.isOpen ? 1 : 0};
`;
class Menu extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
}
open = (event) => {
this.setState({
isOpen: !this.state.isOpen
});
}
getMenuItems = (isSelected, menu, langKey) => {
return menu.map(item => {
const slug = `/${langKey}${item.slug}`;
const subItems = item.items
? (
<ul style={{display: 'none'}}>
{this.getMenuItems(isSelected, item.items, langKey)}
</ul>)
: null;
return (
<li>
<FormattedMessage id={item.label}>
{(label) =>
item.link
? (
<MenuA target="_blank" href={item.link}>
{label}
</MenuA>
)
: (
<MenuLink selected={isSelected(slug)} to={slug} onClick={this.open}>
{label}
</MenuLink>
)
}
</FormattedMessage>
{subItems}
</li>
);
});
}
render() {
const { isOpen } = this.state;
const isSelected = endsWith(this.props.url);
const menuItems = this.getMenuItems(isSelected, this.props.menu, this.props.intl.locale);
return (
<section>
<CloseNav isOpen={isOpen} onClick={this.open} />
<Nav isOpen={isOpen}>
<MenuLabel htmlFor="cb-menu">
<MenuIcon />
<InvisibleSpan>Menu</InvisibleSpan>
<Checkbox type="checkbox" name="cb-menu" id="cb-menu"
checked={this.state.isOpen}
onChange={this.open}
/>
</MenuLabel>
<Ul isOpen={isOpen}>
{menuItems}
</Ul>
</Nav>
</section>
);
}
};
Menu.propTypes = {
menu: PropTypes.array.isRequired,
url: PropTypes.string.isRequired,
intl: PropTypes.object.isRequired
};
export default injectIntl(Menu);
|
Mr.Mining/MikeTheMiner/dist/Santas_helpers/Sia_wallet/resources/app/plugins/Files/js/components/filelist.js | patel344/Mr.Miner | import PropTypes from 'prop-types'
import React from 'react'
import { List, Set } from 'immutable'
import File from './file.js'
import Path from 'path'
import SearchField from '../containers/searchfield.js'
import FileControls from '../containers/filecontrols.js'
import DirectoryInfoBar from './directoryinfobar.js'
const FileList = ({files, selected, searchResults, path, showSearchField, actions}) => {
const onBackClick = () => {
// remove a trailing slash if it exists
const cleanPath = path.replace(/\/$/, '')
if (cleanPath === '') {
return
}
// find the parent directory and set the new path
const pathComponents = cleanPath.split('/')
if (pathComponents.length < 2) {
actions.setPath('')
} else {
actions.setPath(pathComponents[pathComponents.length-2] + '/')
}
}
if (files === null) {
return (
<div className="file-list">
<ul>
<h2> Loading files... </h2>
</ul>
</div>
)
}
let filelistFiles
if (showSearchField) {
filelistFiles = searchResults
} else {
filelistFiles = files
}
const fileElements = filelistFiles.map((file, key) => {
const isSelected = selected.map((selectedfile) => selectedfile.name).includes(file.name)
const onFileClick = (e) => {
const shouldMultiSelect = e.ctrlKey || e.metaKey
const shouldRangeSelect = e.shiftKey
if (!shouldMultiSelect && !shouldRangeSelect) {
actions.deselectAll()
}
if (shouldRangeSelect) {
actions.selectUpTo(file)
}
if (shouldMultiSelect && isSelected) {
actions.deselectFile(file)
} else {
actions.selectFile(file)
}
}
const onDoubleClick = (e) => {
e.stopPropagation()
if (file.type === 'directory') {
actions.setPath(Path.posix.join(path, file.name))
}
}
return (
<File
key={key}
selected={isSelected}
filename={file.name}
filesize={file.size}
redundancy={file.redundancy}
uploadprogress={file.uploadprogress}
available={file.available}
onDoubleClick={onDoubleClick}
type={file.type}
onClick={onFileClick}
/>
)
})
return (
<div className="file-list">
{showSearchField ? <SearchField /> : null}
<ul>
<DirectoryInfoBar path={path} nfiles={files.size} onBackClick={onBackClick} />
{ fileElements.size > 0 ? fileElements : <h2> No files uploaded </h2> }
</ul>
{selected.size > 0 ? <FileControls /> : null}
</div>
)
}
FileList.propTypes = {
files: PropTypes.instanceOf(List),
selected: PropTypes.instanceOf(Set).isRequired,
searchResults: PropTypes.instanceOf(List),
path: PropTypes.string.isRequired,
showSearchField: PropTypes.bool.isRequired,
}
export default FileList
|
src/Button/components/Spacing.js | nkiateam/polestar-antd | import React from 'react';
import PropTypes from 'prop-types';
class Spacing extends React.Component {
static propTypes = {
spacing: PropTypes.number,
};
static defaultProps = {
spacing: 5,
};
constructor(props) {
super(props);
this.state = {};
}
renderChildren = () => {
const { children } = this.props;
return React.Children.map(children, (child, index) => {
const isLast = index + 1 === React.Children.count(children);
return child ? React.cloneElement(child, {
style: {
marginRight: isLast ? '' : this.props.spacing,
marginTop: this.props.spacing,
marginBottom: this.props.spacing,
},
}) : null;
});
};
render() {
return this.renderChildren();
}
}
export default Spacing;
|
src/app/components/share-panel-embed-code.js | pashist/soundcloud-like-player | import React from 'react';
export default class SharePanelEmbedCode extends React.Component {
render() {
if (!this.props.track) return null;
return (
<div className="share-link">
<div className="right">
<input type="checkbox" id="embed-code-wordpress" onClick={this.props.toggleWP}
checked={this.props.isEmbedCodeWordpress}/>
<label htmlFor="embed-code-wordpress">WordPress</label>
<button className="share-embed-code-button" onClick={this.props.onClick}>Link</button>
</div>
<div className="input-wrapper">
<input className="share-link-input" type="text" readOnly="readonly"
value={this.buildEmbedCode()}/>
</div>
</div>
)
}
buildEmbedCode() {
return this.props.isEmbedCodeWordpress
? `[soundcloud url="${this.props.track.uri}" params="color=ff5500" width="100%" height="166" iframe="true" /]`
: `<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=${this.props.track.permalink_url}&color=ff5500"></iframe>`
}
} |
generators/js-framework/modules/react/components/Account/Signup.js | sahat/megaboilerplate | import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import { signup } from '../../actions/auth';
import { facebookLogin, twitterLogin, googleLogin, vkLogin, githubLogin } from '../../actions/oauth';
import Messages from '../Messages';
class Signup extends React.Component {
constructor(props) {
super(props);
this.state = { name: '', email: '', password: '' };
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleSignup(event) {
event.preventDefault();
this.props.dispatch(signup(this.state.name, this.state.email, this.state.password));
}
handleFacebook() {
this.props.dispatch(facebookLogin())
}
handleTwitter() {
this.props.dispatch(twitterLogin())
}
handleGoogle() {
this.props.dispatch(googleLogin())
}
handleVk() {
this.props.dispatch(vkLogin())
}
handleGithub() {
this.props.dispatch(githubLogin())
}
render() {
return (
//= SIGNUP_RENDER_INDENT3
);
}
}
const mapStateToProps = (state) => {
return {
messages: state.messages
};
};
export default connect(mapStateToProps)(Signup);
|
static/src/components/ProtectedView.js | dom-o/hangboard-helper | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionCreators from '../actions/data';
function mapStateToProps(state) {
return {
data: state.data,
token: state.auth.token,
loaded: state.data.loaded,
isFetching: state.data.isFetching,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
@connect(mapStateToProps, mapDispatchToProps)
export default class ProtectedView extends React.Component {
componentDidMount() {
this.fetchData();
}
fetchData() {
const token = this.props.token;
this.props.fetchProtectedData(token);
}
render() {
return (
<div>
{!this.props.loaded
? <h1>Loading data...</h1>
:
<div>
<h1>Welcome back,
{this.props.userName}!</h1>
<h1>{this.props.data.data.email}</h1>
</div>
}
</div>
);
}
}
ProtectedView.propTypes = {
fetchProtectedData: React.PropTypes.func,
loaded: React.PropTypes.bool,
userName: React.PropTypes.string,
data: React.PropTypes.any,
token: React.PropTypes.string,
};
|
app/javascript/mastodon/features/public_timeline/index.js | nonoz/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import {
refreshPublicTimeline,
expandPublicTimeline,
updateTimeline,
deleteFromTimelines,
connectTimeline,
disconnectTimeline,
} from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnSettingsContainer from './containers/column_settings_container';
import createStream from '../../stream';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = state => ({
hasUnread: state.getIn(['timelines', 'public', 'unread']) > 0,
streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']),
accessToken: state.getIn(['meta', 'access_token']),
});
@connect(mapStateToProps)
@injectIntl
export default class PublicTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
streamingAPIBaseURL: PropTypes.string.isRequired,
accessToken: PropTypes.string.isRequired,
hasUnread: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('PUBLIC', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, streamingAPIBaseURL, accessToken } = this.props;
dispatch(refreshPublicTimeline());
if (typeof this._subscription !== 'undefined') {
return;
}
this._subscription = createStream(streamingAPIBaseURL, accessToken, 'public', {
connected () {
dispatch(connectTimeline('public'));
},
reconnected () {
dispatch(connectTimeline('public'));
},
disconnected () {
dispatch(disconnectTimeline('public'));
},
received (data) {
switch(data.event) {
case 'update':
dispatch(updateTimeline('public', JSON.parse(data.payload)));
break;
case 'delete':
dispatch(deleteFromTimelines(data.payload));
break;
}
},
});
}
componentWillUnmount () {
if (typeof this._subscription !== 'undefined') {
this._subscription.close();
this._subscription = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = () => {
this.props.dispatch(expandPublicTimeline());
}
render () {
const { intl, columnId, hasUnread, multiColumn } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer />
</ColumnHeader>
<StatusListContainer
timelineId='public'
loadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other instances to fill it up' />}
/>
</Column>
);
}
}
|
sites/default/files/js/js_UdLmnchi2s8RKaEdBBovoYjZCqJNz54MGRHlttWYkBU.js | piratskul/MyAwesomeDrupal | /*! jQuery v2.2.4 | (c) jQuery Foundation | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||n.uniqueSort(e),D.test(a)&&e.reverse()),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.removeEventListener("DOMContentLoaded",J),a.removeEventListener("load",J),n.ready()}n.ready.promise=function(b){return I||(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",J),a.addEventListener("load",J))),I.promise(b)},n.ready.promise();var K=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)K(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},L=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function M(){this.expando=n.expando+M.uid++}M.uid=1,M.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!L(a))return{};var b=a[this.expando];return b||(b={},L(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(G)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var N=new M,O=new M,P=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Q=/[A-Z]/g;function R(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Q,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:P.test(c)?n.parseJSON(c):c;
}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=N.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function W(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&T.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var X=/^(?:checkbox|radio)$/i,Y=/<([\w:-]+)/,Z=/^$|\/(?:java|ecma)script/i,$={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ja(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ha;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return"undefined"!=typeof n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(G)||[""],j=b.length;while(j--)h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.hasData(a)&&N.get(a);if(r&&(i=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&N.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(N.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||d,e=c.documentElement,f=c.body,a.pageX=b.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ea.test(f)?this.mouseHooks:da.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=d),3===a.target.nodeType&&(a.target=a.target.parentNode),h.filter?h.filter(a,g):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==ia()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===ia()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ga:ha):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:ha,isPropagationStopped:ha,isImmediatePropagationStopped:ha,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ga,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ga,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ga,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),n.fn.extend({on:function(a,b,c,d){return ja(this,a,b,c,d)},one:function(a,b,c,d){return ja(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ha),this.each(function(){n.event.remove(this,a,c,b)})}});var ka=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,la=/<script|<style|<link/i,ma=/checked\s*(?:[^=]|=\s*.checked.)/i,na=/^true\/(.*)/,oa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function pa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function qa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function ra(a){var b=na.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function sa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(N.hasData(a)&&(f=N.access(a),g=N.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}O.hasData(a)&&(h=O.access(a),i=n.extend({},h),O.set(b,i))}}function ta(a,b){var c=b.nodeName.toLowerCase();"input"===c&&X.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ua(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&ma.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ua(f,b,c,d)});if(o&&(e=ca(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map(_(e,"script"),qa),i=h.length;o>m;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,_(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,ra),m=0;i>m;m++)j=h[m],Z.test(j.type||"")&&!N.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(oa,"")))}return a}function va(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(_(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&aa(_(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ka,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=_(h),f=_(a),d=0,e=f.length;e>d;d++)ta(f[d],g[d]);if(b)if(c)for(f=f||_(a),g=g||_(h),d=0,e=f.length;e>d;d++)sa(f[d],g[d]);else sa(a,h);return g=_(h,"script"),g.length>0&&aa(g,!i&&_(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(L(c)){if(b=c[N.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[N.expando]=void 0}c[O.expando]&&(c[O.expando]=void 0)}}}),n.fn.extend({domManip:ua,detach:function(a){return va(this,a,!0)},remove:function(a){return va(this,a)},text:function(a){return K(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.appendChild(a)}})},prepend:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(_(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return K(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!la.test(a)&&!$[(Y.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(_(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ua(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(_(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;f>=h;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var wa,xa={HTML:"block",BODY:"block"};function ya(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function za(a){var b=d,c=xa[a];return c||(c=ya(a,b),"none"!==c&&c||(wa=(wa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=wa[0].contentDocument,b.write(),b.close(),c=ya(a,b),wa.detach()),xa[a]=c),c}var Aa=/^margin/,Ba=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ca=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Da=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Ea=d.documentElement;!function(){var b,c,e,f,g=d.createElement("div"),h=d.createElement("div");if(h.style){h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,g.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",g.appendChild(h);function i(){h.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",h.innerHTML="",Ea.appendChild(g);var d=a.getComputedStyle(h);b="1%"!==d.top,f="2px"===d.marginLeft,c="4px"===d.width,h.style.marginRight="50%",e="4px"===d.marginRight,Ea.removeChild(g)}n.extend(l,{pixelPosition:function(){return i(),b},boxSizingReliable:function(){return null==c&&i(),c},pixelMarginRight:function(){return null==c&&i(),e},reliableMarginLeft:function(){return null==c&&i(),f},reliableMarginRight:function(){var b,c=h.appendChild(d.createElement("div"));return c.style.cssText=h.style.cssText="-webkit-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",h.style.width="1px",Ea.appendChild(g),b=!parseFloat(a.getComputedStyle(c).marginRight),Ea.removeChild(g),h.removeChild(c),b}})}}();function Fa(a,b,c){var d,e,f,g,h=a.style;return c=c||Ca(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Ba.test(g)&&Aa.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0!==g?g+"":g}function Ga(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Ha=/^(none|table(?!-c[ea]).+)/,Ia={position:"absolute",visibility:"hidden",display:"block"},Ja={letterSpacing:"0",fontWeight:"400"},Ka=["Webkit","O","Moz","ms"],La=d.createElement("div").style;function Ma(a){if(a in La)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ka.length;while(c--)if(a=Ka[c]+b,a in La)return a}function Na(a,b,c){var d=T.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Oa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Pa(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ca(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Fa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ba.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Oa(a,b,c||(g?"border":"content"),d,f)+"px"}function Qa(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=N.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=N.access(d,"olddisplay",za(d.nodeName)))):(e=V(d),"none"===c&&e||N.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Fa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=T.exec(c))&&e[1]&&(c=W(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Ma(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Fa(a,b,d)),"normal"===e&&b in Ja&&(e=Ja[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Ha.test(n.css(a,"display"))&&0===a.offsetWidth?Da(a,Ia,function(){return Pa(a,b,d)}):Pa(a,b,d):void 0},set:function(a,c,d){var e,f=d&&Ca(a),g=d&&Oa(a,b,d,"border-box"===n.css(a,"boxSizing",!1,f),f);return g&&(e=T.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=n.css(a,b)),Na(a,c,g)}}}),n.cssHooks.marginLeft=Ga(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Fa(a,"marginLeft"))||a.getBoundingClientRect().left-Da(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px":void 0}),n.cssHooks.marginRight=Ga(l.reliableMarginRight,function(a,b){return b?Da(a,{display:"inline-block"},Fa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Aa.test(a)||(n.cssHooks[a+b].set=Na)}),n.fn.extend({css:function(a,b){return K(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ca(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Qa(this,!0)},hide:function(){return Qa(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function Ra(a,b,c,d,e){return new Ra.prototype.init(a,b,c,d,e)}n.Tween=Ra,Ra.prototype={constructor:Ra,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ra.propHooks[this.prop];return a&&a.get?a.get(this):Ra.propHooks._default.get(this)},run:function(a){var b,c=Ra.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ra.propHooks._default.set(this),this}},Ra.prototype.init.prototype=Ra.prototype,Ra.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},Ra.propHooks.scrollTop=Ra.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=Ra.prototype.init,n.fx.step={};var Sa,Ta,Ua=/^(?:toggle|show|hide)$/,Va=/queueHooks$/;function Wa(){return a.setTimeout(function(){Sa=void 0}),Sa=n.now()}function Xa(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=U[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ya(a,b,c){for(var d,e=(_a.tweeners[b]||[]).concat(_a.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Za(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&V(a),q=N.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?N.get(a,"olddisplay")||za(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Ua.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?za(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=N.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;N.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ya(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function $a(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function _a(a,b,c){var d,e,f=0,g=_a.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Sa||Wa(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:Sa||Wa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for($a(k,j.opts.specialEasing);g>f;f++)if(d=_a.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,Ya,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(_a,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return W(c.elem,a,T.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],_a.tweeners[c]=_a.tweeners[c]||[],_a.tweeners[c].unshift(b)},prefilters:[Za],prefilter:function(a,b){b?_a.prefilters.unshift(a):_a.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=_a(this,n.extend({},a),f);(e||N.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=N.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Va.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=N.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Xa(b,!0),a,d,e)}}),n.each({slideDown:Xa("show"),slideUp:Xa("hide"),slideToggle:Xa("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Sa=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Sa=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ta||(Ta=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(Ta),Ta=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",l.checkOn=""!==a.value,l.optSelected=c.selected,b.disabled=!0,l.optDisabled=!c.disabled,a=d.createElement("input"),a.value="t",a.type="radio",l.radioValue="t"===a.value}();var ab,bb=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return K(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ab:void 0)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)}}),ab={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=bb[b]||n.find.attr;bb[b]=function(a,b,d){var e,f;return d||(f=bb[b],bb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,bb[b]=f),e}});var cb=/^(?:input|select|textarea|button)$/i,db=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return K(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),
void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):cb.test(a.nodeName)||db.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var eb=/[\t\r\n\f]/g;function fb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,fb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,fb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,fb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=fb(this),b&&N.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":N.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+fb(c)+" ").replace(eb," ").indexOf(b)>-1)return!0;return!1}});var gb=/\r/g,hb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(gb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(hb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var ib=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!ib.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||o.trigger.apply(e,c)!==!1)){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,ib.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(N.get(h,"events")||{})[b.type]&&N.get(h,"handle"),m&&m.apply(h,c),m=l&&h[l],m&&m.apply&&L(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!L(e)||l&&n.isFunction(e[q])&&!n.isWindow(e)&&(i=e[l],i&&(e[l]=null),n.event.triggered=q,e[q](),n.event.triggered=void 0,i&&(e[l]=i)),b.result}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b)}}),n.fn.extend({trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),l.focusin="onfocusin"in a,l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=N.access(d,b);e||d.addEventListener(a,c,!0),N.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=N.access(d,b)-1;e?N.access(d,b,e):(d.removeEventListener(a,c,!0),N.remove(d,b))}}});var jb=a.location,kb=n.now(),lb=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var mb=/#.*$/,nb=/([?&])_=[^&]*/,ob=/^(.*?):[ \t]*([^\r\n]*)$/gm,pb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,qb=/^(?:GET|HEAD)$/,rb=/^\/\//,sb={},tb={},ub="*/".concat("*"),vb=d.createElement("a");vb.href=jb.href;function wb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function xb(a,b,c,d){var e={},f=a===tb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function yb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function zb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Ab(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:jb.href,type:"GET",isLocal:pb.test(jb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":ub,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?yb(yb(a,n.ajaxSettings),b):yb(n.ajaxSettings,a)},ajaxPrefilter:wb(sb),ajaxTransport:wb(tb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m=n.ajaxSetup({},c),o=m.context||m,p=m.context&&(o.nodeType||o.jquery)?n(o):n.event,q=n.Deferred(),r=n.Callbacks("once memory"),s=m.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,getResponseHeader:function(a){var b;if(2===v){if(!h){h={};while(b=ob.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===v?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return v||(a=u[c]=u[c]||a,t[a]=b),this},overrideMimeType:function(a){return v||(m.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>v)for(b in a)s[b]=[s[b],a[b]];else x.always(a[x.status]);return this},abort:function(a){var b=a||w;return e&&e.abort(b),z(0,b),this}};if(q.promise(x).complete=r.add,x.success=x.done,x.error=x.fail,m.url=((b||m.url||jb.href)+"").replace(mb,"").replace(rb,jb.protocol+"//"),m.type=c.method||c.type||m.method||m.type,m.dataTypes=n.trim(m.dataType||"*").toLowerCase().match(G)||[""],null==m.crossDomain){j=d.createElement("a");try{j.href=m.url,j.href=j.href,m.crossDomain=vb.protocol+"//"+vb.host!=j.protocol+"//"+j.host}catch(y){m.crossDomain=!0}}if(m.data&&m.processData&&"string"!=typeof m.data&&(m.data=n.param(m.data,m.traditional)),xb(sb,m,c,x),2===v)return x;k=n.event&&m.global,k&&0===n.active++&&n.event.trigger("ajaxStart"),m.type=m.type.toUpperCase(),m.hasContent=!qb.test(m.type),f=m.url,m.hasContent||(m.data&&(f=m.url+=(lb.test(f)?"&":"?")+m.data,delete m.data),m.cache===!1&&(m.url=nb.test(f)?f.replace(nb,"$1_="+kb++):f+(lb.test(f)?"&":"?")+"_="+kb++)),m.ifModified&&(n.lastModified[f]&&x.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&x.setRequestHeader("If-None-Match",n.etag[f])),(m.data&&m.hasContent&&m.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",m.contentType),x.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+ub+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)x.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(m.beforeSend.call(o,x,m)===!1||2===v))return x.abort();w="abort";for(l in{success:1,error:1,complete:1})x[l](m[l]);if(e=xb(tb,m,c,x)){if(x.readyState=1,k&&p.trigger("ajaxSend",[x,m]),2===v)return x;m.async&&m.timeout>0&&(i=a.setTimeout(function(){x.abort("timeout")},m.timeout));try{v=1,e.send(t,z)}catch(y){if(!(2>v))throw y;z(-1,y)}}else z(-1,"No Transport");function z(b,c,d,h){var j,l,t,u,w,y=c;2!==v&&(v=2,i&&a.clearTimeout(i),e=void 0,g=h||"",x.readyState=b>0?4:0,j=b>=200&&300>b||304===b,d&&(u=zb(m,x,d)),u=Ab(m,u,x,j),j?(m.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(n.lastModified[f]=w),w=x.getResponseHeader("etag"),w&&(n.etag[f]=w)),204===b||"HEAD"===m.type?y="nocontent":304===b?y="notmodified":(y=u.state,l=u.data,t=u.error,j=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),x.status=b,x.statusText=(c||y)+"",j?q.resolveWith(o,[l,y,x]):q.rejectWith(o,[x,y,t]),x.statusCode(s),s=void 0,k&&p.trigger(j?"ajaxSuccess":"ajaxError",[x,m,j?l:t]),r.fireWith(o,[x,y]),k&&(p.trigger("ajaxComplete",[x,m]),--n.active||n.event.trigger("ajaxStop")))}return x},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return!n.expr.filters.visible(a)},n.expr.filters.visible=function(a){return a.offsetWidth>0||a.offsetHeight>0||a.getClientRects().length>0};var Bb=/%20/g,Cb=/\[\]$/,Db=/\r?\n/g,Eb=/^(?:submit|button|image|reset|file)$/i,Fb=/^(?:input|select|textarea|keygen)/i;function Gb(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Cb.test(a)?d(a,e):Gb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Gb(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Gb(c,a[c],b,e);return d.join("&").replace(Bb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Fb.test(this.nodeName)&&!Eb.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Db,"\r\n")}}):{name:b.name,value:c.replace(Db,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Hb={0:200,1223:204},Ib=n.ajaxSettings.xhr();l.cors=!!Ib&&"withCredentials"in Ib,l.ajax=Ib=!!Ib,n.ajaxTransport(function(b){var c,d;return l.cors||Ib&&!b.crossDomain?{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Hb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=n("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Jb=[],Kb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Jb.pop()||n.expando+"_"+kb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Kb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Kb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Kb,"$1"+e):b.jsonp!==!1&&(b.url+=(lb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Jb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ca([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var Lb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Lb)return Lb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function Mb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(e=d.getBoundingClientRect(),c=Mb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ea})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;n.fn[a]=function(d){return K(this,function(a,d,e){var f=Mb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ga(l.pixelPosition,function(a,c){return c?(c=Fa(a,b),Ba.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return K(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)},size:function(){return this.length}}),n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Nb=a.jQuery,Ob=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Ob),b&&a.jQuery===n&&(a.jQuery=Nb),n},b||(a.jQuery=a.$=n),n});
;
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])<u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e<arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this);
(function(t){var e=typeof self=="object"&&self.self==self&&self||typeof global=="object"&&global.global==global&&global;if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,n){e.Backbone=t(e,n,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore"),r;try{r=require("jquery")}catch(n){}t(e,exports,i,r)}else{e.Backbone=t(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}})(function(t,e,i,r){var n=t.Backbone;var s=Array.prototype.slice;e.VERSION="1.2.3";e.$=r;e.noConflict=function(){t.Backbone=n;return this};e.emulateHTTP=false;e.emulateJSON=false;var a=function(t,e,r){switch(t){case 1:return function(){return i[e](this[r])};case 2:return function(t){return i[e](this[r],t)};case 3:return function(t,n){return i[e](this[r],h(t,this),n)};case 4:return function(t,n,s){return i[e](this[r],h(t,this),n,s)};default:return function(){var t=s.call(arguments);t.unshift(this[r]);return i[e].apply(i,t)}}};var o=function(t,e,r){i.each(e,function(e,n){if(i[n])t.prototype[n]=a(e,n,r)})};var h=function(t,e){if(i.isFunction(t))return t;if(i.isObject(t)&&!e._isModel(t))return u(t);if(i.isString(t))return function(e){return e.get(t)};return t};var u=function(t){var e=i.matches(t);return function(t){return e(t.attributes)}};var l=e.Events={};var c=/\s+/;var f=function(t,e,r,n,s){var a=0,o;if(r&&typeof r==="object"){if(n!==void 0&&"context"in s&&s.context===void 0)s.context=n;for(o=i.keys(r);a<o.length;a++){e=f(t,e,o[a],r[o[a]],s)}}else if(r&&c.test(r)){for(o=r.split(c);a<o.length;a++){e=t(e,o[a],n,s)}}else{e=t(e,r,n,s)}return e};l.on=function(t,e,i){return d(this,t,e,i)};var d=function(t,e,i,r,n){t._events=f(v,t._events||{},e,i,{context:r,ctx:t,listening:n});if(n){var s=t._listeners||(t._listeners={});s[n.id]=n}return t};l.listenTo=function(t,e,r){if(!t)return this;var n=t._listenId||(t._listenId=i.uniqueId("l"));var s=this._listeningTo||(this._listeningTo={});var a=s[n];if(!a){var o=this._listenId||(this._listenId=i.uniqueId("l"));a=s[n]={obj:t,objId:n,id:o,listeningTo:s,count:0}}d(t,e,r,this,a);return this};var v=function(t,e,i,r){if(i){var n=t[e]||(t[e]=[]);var s=r.context,a=r.ctx,o=r.listening;if(o)o.count++;n.push({callback:i,context:s,ctx:s||a,listening:o})}return t};l.off=function(t,e,i){if(!this._events)return this;this._events=f(g,this._events,t,e,{context:i,listeners:this._listeners});return this};l.stopListening=function(t,e,r){var n=this._listeningTo;if(!n)return this;var s=t?[t._listenId]:i.keys(n);for(var a=0;a<s.length;a++){var o=n[s[a]];if(!o)break;o.obj.off(e,r,this)}if(i.isEmpty(n))this._listeningTo=void 0;return this};var g=function(t,e,r,n){if(!t)return;var s=0,a;var o=n.context,h=n.listeners;if(!e&&!r&&!o){var u=i.keys(h);for(;s<u.length;s++){a=h[u[s]];delete h[a.id];delete a.listeningTo[a.objId]}return}var l=e?[e]:i.keys(t);for(;s<l.length;s++){e=l[s];var c=t[e];if(!c)break;var f=[];for(var d=0;d<c.length;d++){var v=c[d];if(r&&r!==v.callback&&r!==v.callback._callback||o&&o!==v.context){f.push(v)}else{a=v.listening;if(a&&--a.count===0){delete h[a.id];delete a.listeningTo[a.objId]}}}if(f.length){t[e]=f}else{delete t[e]}}if(i.size(t))return t};l.once=function(t,e,r){var n=f(p,{},t,e,i.bind(this.off,this));return this.on(n,void 0,r)};l.listenToOnce=function(t,e,r){var n=f(p,{},e,r,i.bind(this.stopListening,this,t));return this.listenTo(t,n)};var p=function(t,e,r,n){if(r){var s=t[e]=i.once(function(){n(e,s);r.apply(this,arguments)});s._callback=r}return t};l.trigger=function(t){if(!this._events)return this;var e=Math.max(0,arguments.length-1);var i=Array(e);for(var r=0;r<e;r++)i[r]=arguments[r+1];f(m,this._events,t,void 0,i);return this};var m=function(t,e,i,r){if(t){var n=t[e];var s=t.all;if(n&&s)s=s.slice();if(n)_(n,r);if(s)_(s,[e].concat(r))}return t};var _=function(t,e){var i,r=-1,n=t.length,s=e[0],a=e[1],o=e[2];switch(e.length){case 0:while(++r<n)(i=t[r]).callback.call(i.ctx);return;case 1:while(++r<n)(i=t[r]).callback.call(i.ctx,s);return;case 2:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a);return;case 3:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a,o);return;default:while(++r<n)(i=t[r]).callback.apply(i.ctx,e);return}};l.bind=l.on;l.unbind=l.off;i.extend(e,l);var y=e.Model=function(t,e){var r=t||{};e||(e={});this.cid=i.uniqueId(this.cidPrefix);this.attributes={};if(e.collection)this.collection=e.collection;if(e.parse)r=this.parse(r,e)||{};r=i.defaults({},r,i.result(this,"defaults"));this.set(r,e);this.changed={};this.initialize.apply(this,arguments)};i.extend(y.prototype,l,{changed:null,validationError:null,idAttribute:"id",cidPrefix:"c",initialize:function(){},toJSON:function(t){return i.clone(this.attributes)},sync:function(){return e.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return i.escape(this.get(t))},has:function(t){return this.get(t)!=null},matches:function(t){return!!i.iteratee(t,this)(this.attributes)},set:function(t,e,r){if(t==null)return this;var n;if(typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r||(r={});if(!this._validate(n,r))return false;var s=r.unset;var a=r.silent;var o=[];var h=this._changing;this._changing=true;if(!h){this._previousAttributes=i.clone(this.attributes);this.changed={}}var u=this.attributes;var l=this.changed;var c=this._previousAttributes;for(var f in n){e=n[f];if(!i.isEqual(u[f],e))o.push(f);if(!i.isEqual(c[f],e)){l[f]=e}else{delete l[f]}s?delete u[f]:u[f]=e}this.id=this.get(this.idAttribute);if(!a){if(o.length)this._pending=r;for(var d=0;d<o.length;d++){this.trigger("change:"+o[d],this,u[o[d]],r)}}if(h)return this;if(!a){while(this._pending){r=this._pending;this._pending=false;this.trigger("change",this,r)}}this._pending=false;this._changing=false;return this},unset:function(t,e){return this.set(t,void 0,i.extend({},e,{unset:true}))},clear:function(t){var e={};for(var r in this.attributes)e[r]=void 0;return this.set(e,i.extend({},t,{unset:true}))},hasChanged:function(t){if(t==null)return!i.isEmpty(this.changed);return i.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?i.clone(this.changed):false;var e=this._changing?this._previousAttributes:this.attributes;var r={};for(var n in t){var s=t[n];if(i.isEqual(e[n],s))continue;r[n]=s}return i.size(r)?r:false},previous:function(t){if(t==null||!this._previousAttributes)return null;return this._previousAttributes[t]},previousAttributes:function(){return i.clone(this._previousAttributes)},fetch:function(t){t=i.extend({parse:true},t);var e=this;var r=t.success;t.success=function(i){var n=t.parse?e.parse(i,t):i;if(!e.set(n,t))return false;if(r)r.call(t.context,e,i,t);e.trigger("sync",e,i,t)};z(this,t);return this.sync("read",this,t)},save:function(t,e,r){var n;if(t==null||typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r=i.extend({validate:true,parse:true},r);var s=r.wait;if(n&&!s){if(!this.set(n,r))return false}else{if(!this._validate(n,r))return false}var a=this;var o=r.success;var h=this.attributes;r.success=function(t){a.attributes=h;var e=r.parse?a.parse(t,r):t;if(s)e=i.extend({},n,e);if(e&&!a.set(e,r))return false;if(o)o.call(r.context,a,t,r);a.trigger("sync",a,t,r)};z(this,r);if(n&&s)this.attributes=i.extend({},h,n);var u=this.isNew()?"create":r.patch?"patch":"update";if(u==="patch"&&!r.attrs)r.attrs=n;var l=this.sync(u,this,r);this.attributes=h;return l},destroy:function(t){t=t?i.clone(t):{};var e=this;var r=t.success;var n=t.wait;var s=function(){e.stopListening();e.trigger("destroy",e,e.collection,t)};t.success=function(i){if(n)s();if(r)r.call(t.context,e,i,t);if(!e.isNew())e.trigger("sync",e,i,t)};var a=false;if(this.isNew()){i.defer(t.success)}else{z(this,t);a=this.sync("delete",this,t)}if(!n)s();return a},url:function(){var t=i.result(this,"urlRoot")||i.result(this.collection,"url")||F();if(this.isNew())return t;var e=this.get(this.idAttribute);return t.replace(/[^\/]$/,"$&/")+encodeURIComponent(e)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(t){return this._validate({},i.defaults({validate:true},t))},_validate:function(t,e){if(!e.validate||!this.validate)return true;t=i.extend({},this.attributes,t);var r=this.validationError=this.validate(t,e)||null;if(!r)return true;this.trigger("invalid",this,r,i.extend(e,{validationError:r}));return false}});var b={keys:1,values:1,pairs:1,invert:1,pick:0,omit:0,chain:1,isEmpty:1};o(y,b,"attributes");var x=e.Collection=function(t,e){e||(e={});if(e.model)this.model=e.model;if(e.comparator!==void 0)this.comparator=e.comparator;this._reset();this.initialize.apply(this,arguments);if(t)this.reset(t,i.extend({silent:true},e))};var w={add:true,remove:true,merge:true};var E={add:true,remove:false};var k=function(t,e,i){i=Math.min(Math.max(i,0),t.length);var r=Array(t.length-i);var n=e.length;for(var s=0;s<r.length;s++)r[s]=t[s+i];for(s=0;s<n;s++)t[s+i]=e[s];for(s=0;s<r.length;s++)t[s+n+i]=r[s]};i.extend(x.prototype,l,{model:y,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return e.sync.apply(this,arguments)},add:function(t,e){return this.set(t,i.extend({merge:false},e,E))},remove:function(t,e){e=i.extend({},e);var r=!i.isArray(t);t=r?[t]:i.clone(t);var n=this._removeModels(t,e);if(!e.silent&&n)this.trigger("update",this,e);return r?n[0]:n},set:function(t,e){if(t==null)return;e=i.defaults({},e,w);if(e.parse&&!this._isModel(t))t=this.parse(t,e);var r=!i.isArray(t);t=r?[t]:t.slice();var n=e.at;if(n!=null)n=+n;if(n<0)n+=this.length+1;var s=[];var a=[];var o=[];var h={};var u=e.add;var l=e.merge;var c=e.remove;var f=false;var d=this.comparator&&n==null&&e.sort!==false;var v=i.isString(this.comparator)?this.comparator:null;var g;for(var p=0;p<t.length;p++){g=t[p];var m=this.get(g);if(m){if(l&&g!==m){var _=this._isModel(g)?g.attributes:g;if(e.parse)_=m.parse(_,e);m.set(_,e);if(d&&!f)f=m.hasChanged(v)}if(!h[m.cid]){h[m.cid]=true;s.push(m)}t[p]=m}else if(u){g=t[p]=this._prepareModel(g,e);if(g){a.push(g);this._addReference(g,e);h[g.cid]=true;s.push(g)}}}if(c){for(p=0;p<this.length;p++){g=this.models[p];if(!h[g.cid])o.push(g)}if(o.length)this._removeModels(o,e)}var y=false;var b=!d&&u&&c;if(s.length&&b){y=this.length!=s.length||i.some(this.models,function(t,e){return t!==s[e]});this.models.length=0;k(this.models,s,0);this.length=this.models.length}else if(a.length){if(d)f=true;k(this.models,a,n==null?this.length:n);this.length=this.models.length}if(f)this.sort({silent:true});if(!e.silent){for(p=0;p<a.length;p++){if(n!=null)e.index=n+p;g=a[p];g.trigger("add",g,this,e)}if(f||y)this.trigger("sort",this,e);if(a.length||o.length)this.trigger("update",this,e)}return r?t[0]:t},reset:function(t,e){e=e?i.clone(e):{};for(var r=0;r<this.models.length;r++){this._removeReference(this.models[r],e)}e.previousModels=this.models;this._reset();t=this.add(t,i.extend({silent:true},e));if(!e.silent)this.trigger("reset",this,e);return t},push:function(t,e){return this.add(t,i.extend({at:this.length},e))},pop:function(t){var e=this.at(this.length-1);return this.remove(e,t)},unshift:function(t,e){return this.add(t,i.extend({at:0},e))},shift:function(t){var e=this.at(0);return this.remove(e,t)},slice:function(){return s.apply(this.models,arguments)},get:function(t){if(t==null)return void 0;var e=this.modelId(this._isModel(t)?t.attributes:t);return this._byId[t]||this._byId[e]||this._byId[t.cid]},at:function(t){if(t<0)t+=this.length;return this.models[t]},where:function(t,e){return this[e?"find":"filter"](t)},findWhere:function(t){return this.where(t,true)},sort:function(t){var e=this.comparator;if(!e)throw new Error("Cannot sort a set without a comparator");t||(t={});var r=e.length;if(i.isFunction(e))e=i.bind(e,this);if(r===1||i.isString(e)){this.models=this.sortBy(e)}else{this.models.sort(e)}if(!t.silent)this.trigger("sort",this,t);return this},pluck:function(t){return i.invoke(this.models,"get",t)},fetch:function(t){t=i.extend({parse:true},t);var e=t.success;var r=this;t.success=function(i){var n=t.reset?"reset":"set";r[n](i,t);if(e)e.call(t.context,r,i,t);r.trigger("sync",r,i,t)};z(this,t);return this.sync("read",this,t)},create:function(t,e){e=e?i.clone(e):{};var r=e.wait;t=this._prepareModel(t,e);if(!t)return false;if(!r)this.add(t,e);var n=this;var s=e.success;e.success=function(t,e,i){if(r)n.add(t,i);if(s)s.call(i.context,t,e,i)};t.save(null,e);return t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models,{model:this.model,comparator:this.comparator})},modelId:function(t){return t[this.model.prototype.idAttribute||"id"]},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(t,e){if(this._isModel(t)){if(!t.collection)t.collection=this;return t}e=e?i.clone(e):{};e.collection=this;var r=new this.model(t,e);if(!r.validationError)return r;this.trigger("invalid",this,r.validationError,e);return false},_removeModels:function(t,e){var i=[];for(var r=0;r<t.length;r++){var n=this.get(t[r]);if(!n)continue;var s=this.indexOf(n);this.models.splice(s,1);this.length--;if(!e.silent){e.index=s;n.trigger("remove",n,this,e)}i.push(n);this._removeReference(n,e)}return i.length?i:false},_isModel:function(t){return t instanceof y},_addReference:function(t,e){this._byId[t.cid]=t;var i=this.modelId(t.attributes);if(i!=null)this._byId[i]=t;t.on("all",this._onModelEvent,this)},_removeReference:function(t,e){delete this._byId[t.cid];var i=this.modelId(t.attributes);if(i!=null)delete this._byId[i];if(this===t.collection)delete t.collection;t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,r){if((t==="add"||t==="remove")&&i!==this)return;if(t==="destroy")this.remove(e,r);if(t==="change"){var n=this.modelId(e.previousAttributes());var s=this.modelId(e.attributes);if(n!==s){if(n!=null)delete this._byId[n];if(s!=null)this._byId[s]=e}}this.trigger.apply(this,arguments)}});var S={forEach:3,each:3,map:3,collect:3,reduce:4,foldl:4,inject:4,reduceRight:4,foldr:4,find:3,detect:3,filter:3,select:3,reject:3,every:3,all:3,some:3,any:3,include:3,includes:3,contains:3,invoke:0,max:3,min:3,toArray:1,size:1,first:3,head:3,take:3,initial:3,rest:3,tail:3,drop:3,last:3,without:0,difference:0,indexOf:3,shuffle:1,lastIndexOf:3,isEmpty:1,chain:1,sample:3,partition:3,groupBy:3,countBy:3,sortBy:3,indexBy:3};o(x,S,"models");var I=e.View=function(t){this.cid=i.uniqueId("view");i.extend(this,i.pick(t,P));this._ensureElement();this.initialize.apply(this,arguments)};var T=/^(\S+)\s*(.*)$/;var P=["model","collection","el","id","attributes","className","tagName","events"];i.extend(I.prototype,l,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){this._removeElement();this.stopListening();return this},_removeElement:function(){this.$el.remove()},setElement:function(t){this.undelegateEvents();this._setElement(t);this.delegateEvents();return this},_setElement:function(t){this.$el=t instanceof e.$?t:e.$(t);this.el=this.$el[0]},delegateEvents:function(t){t||(t=i.result(this,"events"));if(!t)return this;this.undelegateEvents();for(var e in t){var r=t[e];if(!i.isFunction(r))r=this[r];if(!r)continue;var n=e.match(T);this.delegate(n[1],n[2],i.bind(r,this))}return this},delegate:function(t,e,i){this.$el.on(t+".delegateEvents"+this.cid,e,i);return this},undelegateEvents:function(){if(this.$el)this.$el.off(".delegateEvents"+this.cid);return this},undelegate:function(t,e,i){this.$el.off(t+".delegateEvents"+this.cid,e,i);return this},_createElement:function(t){return document.createElement(t)},_ensureElement:function(){if(!this.el){var t=i.extend({},i.result(this,"attributes"));if(this.id)t.id=i.result(this,"id");if(this.className)t["class"]=i.result(this,"className");this.setElement(this._createElement(i.result(this,"tagName")));this._setAttributes(t)}else{this.setElement(i.result(this,"el"))}},_setAttributes:function(t){this.$el.attr(t)}});e.sync=function(t,r,n){var s=H[t];i.defaults(n||(n={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:s,dataType:"json"};if(!n.url){a.url=i.result(r,"url")||F()}if(n.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(n.attrs||r.toJSON(n))}if(n.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(n.emulateHTTP&&(s==="PUT"||s==="DELETE"||s==="PATCH")){a.type="POST";if(n.emulateJSON)a.data._method=s;var o=n.beforeSend;n.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",s);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!n.emulateJSON){a.processData=false}var h=n.error;n.error=function(t,e,i){n.textStatus=e;n.errorThrown=i;if(h)h.call(n.context,t,e,i)};var u=n.xhr=e.ajax(i.extend(a,n));r.trigger("request",r,u,n);return u};var H={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var A=/\((.*?)\)/g;var C=/(\(\?)?:\w+/g;var R=/\*\w+/g;var j=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,l,{initialize:function(){},route:function(t,r,n){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){n=r;r=""}if(!n)n=this[r];var s=this;e.history.route(t,function(i){var a=s._extractParameters(t,i);if(s.execute(n,a,r)!==false){s.trigger.apply(s,["route:"+r].concat(a));s.trigger("route",r,a);e.history.trigger("route",s,r,a)}});return this},execute:function(t,e,i){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(j,"\\$&").replace(A,"(?:$1)?").replace(C,function(t,e){return e?t:"([^/?]+)"}).replace(R,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var M=e.History=function(){this.handlers=[];this.checkUrl=i.bind(this.checkUrl,this);if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var N=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var U=/#.*$/;M.started=false;i.extend(M.prototype,l,{interval:50,atRoot:function(){var t=this.location.pathname.replace(/[^\/]$/,"$&/");return t===this.root&&!this.getSearch()},matchRoot:function(){var t=this.decodeFragment(this.location.pathname);var e=t.slice(0,this.root.length-1)+"/";return e===this.root},decodeFragment:function(t){return decodeURI(t.replace(/%25/g,"%2525"))},getSearch:function(){var t=this.location.href.replace(/#.*/,"").match(/\?.+/);return t?t[0]:""},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getPath:function(){var t=this.decodeFragment(this.location.pathname+this.getSearch()).slice(this.root.length-1);return t.charAt(0)==="/"?t.slice(1):t},getFragment:function(t){if(t==null){if(this._usePushState||!this._wantsHashChange){t=this.getPath()}else{t=this.getHash()}}return t.replace(N,"")},start:function(t){if(M.started)throw new Error("Backbone.history has already been started");M.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._hasHashChange="onhashchange"in window&&(document.documentMode===void 0||document.documentMode>7);this._useHashChange=this._wantsHashChange&&this._hasHashChange;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.history&&this.history.pushState);this._usePushState=this._wantsPushState&&this._hasPushState;this.fragment=this.getFragment();this.root=("/"+this.root+"/").replace(O,"/");if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||"/";this.location.replace(e+"#"+this.getPath());return true}else if(this._hasPushState&&this.atRoot()){this.navigate(this.getHash(),{replace:true})}}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe");this.iframe.src="javascript:0";this.iframe.style.display="none";this.iframe.tabIndex=-1;var r=document.body;var n=r.insertBefore(this.iframe,r.firstChild).contentWindow;n.document.open();n.document.close();n.location.hash="#"+this.fragment}var s=window.addEventListener||function(t,e){return attachEvent("on"+t,e)};if(this._usePushState){s("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){s("hashchange",this.checkUrl,false)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}if(!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent("on"+t,e)};if(this._usePushState){t("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){t("hashchange",this.checkUrl,false)}if(this.iframe){document.body.removeChild(this.iframe);this.iframe=null}if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);M.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getHash(this.iframe.contentWindow)}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){if(!this.matchRoot())return false;t=this.fragment=this.getFragment(t);return i.some(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!M.started)return false;if(!e||e===true)e={trigger:!!e};t=this.getFragment(t||"");var i=this.root;if(t===""||t.charAt(0)==="?"){i=i.slice(0,-1)||"/"}var r=i+t;t=this.decodeFragment(t.replace(U,""));if(this.fragment===t)return;this.fragment=t;if(this._usePushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,r)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var n=this.iframe.contentWindow;if(!e.replace){n.document.open();n.document.close()}this._updateHash(n.location,t,e.replace)}}else{return this.location.assign(r)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});e.history=new M;var q=function(t,e){var r=this;var n;if(t&&i.has(t,"constructor")){n=t.constructor}else{n=function(){return r.apply(this,arguments)}}i.extend(n,r,e);var s=function(){this.constructor=n};s.prototype=r.prototype;n.prototype=new s;if(t)i.extend(n.prototype,t);n.__super__=r.prototype;return n};y.extend=x.extend=$.extend=I.extend=M.extend=q;var F=function(){throw new Error('A "url" property or function must be specified')};var z=function(t,e){var i=e.error;e.error=function(r){if(i)i.call(e.context,t,r,e);t.trigger("error",t,r,e)}};return e});
/*!
* jQuery Once v2.1.1 - http://github.com/robloach/jquery-once
* @license MIT, GPL-2.0
* http://opensource.org/licenses/MIT
* http://opensource.org/licenses/GPL-2.0
*/
(function(e){"use strict";if(typeof exports==="object"){e(require("jquery"))}else if(typeof define==="function"&&define.amd){define(["jquery"],e)}else{e(jQuery)}})(function(e){"use strict";var n=function(e){e=e||"once";if(typeof e!=="string"){throw new Error("The jQuery Once id parameter must be a string")}return e};e.fn.once=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)!==true}).data(r,true)};e.fn.removeOnce=function(e){return this.findOnce(e).removeData("jquery-once-"+n(e))};e.fn.findOnce=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)===true})}});
/**
* @file
* Parse inline JSON and initialize the drupalSettings global object.
*/
(function () {
'use strict';
// Use direct child elements to harden against XSS exploits when CSP is on.
var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');
/**
* Variable generated by Drupal with all the configuration created from PHP.
*
* @global
*
* @type {object}
*/
window.drupalSettings = {};
if (settingsElement !== null) {
window.drupalSettings = JSON.parse(settingsElement.textContent);
}
})();
;
window.drupalTranslations = {"strings":{"":{"An AJAX HTTP error occurred.":"\u0412\u043e\u0437\u043d\u0438\u043a\u043b\u0430 AJAX HTTP \u043e\u0448\u0438\u0431\u043a\u0430.","HTTP Result Code: !status":"\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u043a\u043e\u0434 HTTP: !status","An AJAX HTTP request terminated abnormally.":"AJAX HTTP-\u0437\u0430\u043f\u0440\u043e\u0441 \u043d\u0435\u043e\u0436\u0438\u0434\u0430\u043d\u043d\u043e \u0437\u0430\u0432\u0435\u0440\u0448\u0451\u043d.","Debugging information follows.":"\u0421\u043b\u0435\u0434\u0443\u0435\u0442 \u043e\u0442\u043b\u0430\u0434\u043e\u0447\u043d\u0430\u044f \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f.","Path: !uri":"\u041f\u0443\u0442\u044c: !uri","StatusText: !statusText":"\u0422\u0435\u043a\u0441\u0442 \u0421\u043e\u0441\u0442\u043e\u044f\u043d\u0438\u044f: !statusText","ResponseText: !responseText":"\u0422\u0435\u043a\u0441\u0442 \u041e\u0442\u0432\u0435\u0442\u0430: !responseText","ReadyState: !readyState":"ReadyState: !readyState","CustomMessage: !customMessage":"\u0421\u043e\u0431\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435: !customMessage","Please wait...":"\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u043f\u043e\u0434\u043e\u0436\u0434\u0438\u0442\u0435...","The response failed verification so will not be processed.":"\u041e\u0442\u0432\u0435\u0442 \u043d\u0435 \u043f\u0440\u043e\u0448\u0435\u043b \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0443 \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u043e\u0431\u0440\u0430\u0431\u0430\u0442\u044b\u0432\u0430\u0442\u044c\u0441\u044f \u043d\u0435 \u0431\u0443\u0434\u0435\u0442.","The callback URL is not local and not trusted: !url":"URL-\u0430\u0434\u0440\u0435\u0441 \u043e\u0431\u0440\u0430\u0442\u043d\u043e\u0433\u043e \u0432\u044b\u0437\u043e\u0432\u0430 \u043d\u0435 \u044f\u0432\u043b\u044f\u0435\u0442\u0441\u044f \u043b\u043e\u043a\u0430\u043b\u044c\u043d\u044b\u043c \u0438 \u0434\u043e\u0432\u0435\u0440\u0435\u043d\u043d\u044b\u043c: !url","Changed":"\u0418\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435","Home":"\u0413\u043b\u0430\u0432\u043d\u0430\u044f","Next":"\u0412\u043f\u0435\u0440\u0451\u0434","closed":"\u0437\u0430\u043a\u0440\u044b\u0442\u043e","Cancel":"\u041e\u0442\u043c\u0435\u043d\u0430","Edit":"\u0420\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c","Link":"\u0421\u0441\u044b\u043b\u043a\u0430","Image":"\u0418\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435","Save":"\u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c","Open":"\u041e\u0442\u043a\u0440\u044b\u0442\u044c","Sunday":"\u0432\u043e\u0441\u043a\u0440\u0435\u0441\u0435\u043d\u044c\u0435","Monday":"\u043f\u043e\u043d\u0435\u0434\u0435\u043b\u044c\u043d\u0438\u043a","Tuesday":"\u0432\u0442\u043e\u0440\u043d\u0438\u043a","Wednesday":"\u0441\u0440\u0435\u0434\u0430","Thursday":"\u0447\u0435\u0442\u0432\u0435\u0440\u0433","Friday":"\u043f\u044f\u0442\u043d\u0438\u0446\u0430","Saturday":"\u0441\u0443\u0431\u0431\u043e\u0442\u0430","Add":"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c","Continue":"\u041f\u0440\u043e\u0434\u043e\u043b\u0436\u0438\u0442\u044c","Done":"\u0413\u043e\u0442\u043e\u0432\u043e","OK":"OK","Prev":"\u041d\u0430\u0437\u0430\u0434","Mon":"\u043f\u043d","Tue":"\u0432\u0442","Wed":"\u0441\u0440","Thu":"\u0447\u0442","Fri":"\u043f\u0442","Sat":"\u0441\u0431","Sun":"\u0432\u0441","May":"\u043c\u0430\u044f","Close":"\u0417\u0430\u043a\u0440\u044b\u0442\u044c","Show":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c","Select all rows in this table":"\u041e\u0442\u043c\u0435\u0442\u0438\u0442\u044c \u0432\u0441\u0435 \u0441\u0442\u0440\u043e\u043a\u0438 \u0442\u0430\u0431\u043b\u0438\u0446\u044b","Deselect all rows in this table":"\u0421\u043d\u044f\u0442\u044c \u043e\u0442\u043c\u0435\u0442\u043a\u0443 \u0441\u043e \u0432\u0441\u0435\u0445 \u043a\u043e\u043b\u043e\u043d\u043e\u043a \u0442\u0430\u0431\u043b\u0438\u0446\u044b","Today":"\u0421\u0435\u0433\u043e\u0434\u043d\u044f","Jan":"\u044f\u043d\u0432","Feb":"\u0444\u0435\u0432","Mar":"\u043c\u0430\u0440","Apr":"\u0430\u043f\u0440","Jun":"\u0438\u044e\u043d","Jul":"\u0438\u044e\u043b","Aug":"\u0430\u0432\u0433","Sep":"\u0441\u0435\u043d","Oct":"\u043e\u043a\u0442","Nov":"\u043d\u043e\u044f","Dec":"\u0434\u0435\u043a","Extend":"\u0420\u0430\u0441\u0448\u0438\u0440\u0438\u0442\u044c","Su":"\u0432\u0441","Mo":"\u043f\u043d","Tu":"\u0432\u0442","We":"\u0441\u0440","Th":"\u0447\u0442","Fr":"\u043f\u0442","Sa":"\u0441\u0431","Not published":"\u041d\u0435 \u043e\u043f\u0443\u0431\u043b\u0438\u043a\u043e\u0432\u0430\u043d\u043e","Loading...":"\u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430...","Hide":"\u0421\u043a\u0440\u044b\u0442\u044c","1 new comment\u0003@count new comments":"@count \u043d\u043e\u0432\u044b\u0439 \u043a\u043e\u043c\u043c\u0435\u043d\u0442\u0430\u0440\u0438\u0439\u0003@count \u043d\u043e\u0432\u044b\u0445 \u043a\u043e\u043c\u043c\u0435\u043d\u0442\u0430\u0440\u0438\u044f\u0003@count[2] \u043d\u043e\u0432\u044b\u0445 \u043a\u043e\u043c\u043c\u0435\u043d\u0442\u0430\u0440\u0438\u0435\u0432","Unlink":"\u041e\u0442\u0432\u044f\u0437\u0430\u0442\u044c","Not promoted":"\u041d\u0435 \u0432\u044b\u0432\u0435\u0434\u0435\u043d\u043e \u043d\u0430 \u0433\u043b\u0430\u0432\u043d\u0443\u044e","mm\/dd\/yy":"mm\/dd\/yy","Error message":"\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0431 \u043e\u0448\u0438\u0431\u043a\u0435","Quick edit":"\u0411\u044b\u0441\u0442\u0440\u043e\u0435 \u0440\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435","Edit Link":"\u0420\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0441\u0441\u044b\u043b\u043a\u0443","Remove group":"\u0423\u0434\u0430\u043b\u0438\u0442\u044c \u0433\u0440\u0443\u043f\u043f\u0443","By @name on @date":"@name, @date","By @name":"@name","Not in menu":"\u041d\u0435 \u0432 \u043c\u0435\u043d\u044e","Alias: @alias":"\u0421\u0438\u043d\u043e\u043d\u0438\u043c: @alias","No alias":"\u0421\u0438\u043d\u043e\u043d\u0438\u043c \u043d\u0435 \u0437\u0430\u0434\u0430\u043d","@label":"@label","New revision":"\u041d\u043e\u0432\u0430\u044f \u0440\u0435\u0434\u0430\u043a\u0446\u0438\u044f","Drag to re-order":"\u0418\u0437\u043c\u0435\u043d\u0438\u0442\u044c \u043f\u043e\u0440\u044f\u0434\u043e\u043a \u043c\u043e\u0436\u043d\u043e, \u043f\u0435\u0440\u0435\u0442\u0430\u0449\u0438\u0432 \u043f\u0443\u043d\u043a\u0442 \u043c\u044b\u0448\u043a\u043e\u0439.","Discard changes":"\u041e\u0442\u043c\u0435\u043d\u0438\u0442\u044c \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f","Breadcrumbs":"Breadcrumbs","Saving":"\u0421\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u0435","No revision":"\u041d\u0435\u0442 \u0440\u0435\u0434\u0430\u043a\u0446\u0438\u0438","Requires a title":"\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0437\u0430\u0433\u043e\u043b\u043e\u0432\u043e\u043a","Not restricted":"\u0411\u0435\u0437 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0439","(active tab)":"(\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0432\u043a\u043b\u0430\u0434\u043a\u0430)","Restricted to certain pages":"\u041e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u043e \u0434\u043b\u044f \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0451\u043d\u043d\u044b\u0445 \u0441\u0442\u0440\u0430\u043d\u0438\u0446","The block cannot be placed in this region.":"\u0411\u043b\u043e\u043a \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0440\u0430\u0437\u043c\u0435\u0449\u0451\u043d \u0432 \u0434\u0430\u043d\u043d\u043e\u0439 \u043e\u0431\u043b\u0430\u0441\u0442\u0438.","Hide summary":"\u0421\u043a\u0440\u044b\u0442\u044c \u0430\u043d\u043e\u043d\u0441","Edit summary":"\u0420\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0430\u043d\u043e\u043d\u0441","Don\u0027t display post information":"\u041d\u0435 \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0442\u044c \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u043e \u043f\u0443\u0431\u043b\u0438\u043a\u0430\u0446\u0438\u0438","Collapse":"\u0421\u0432\u0435\u0440\u043d\u0443\u0442\u044c","The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.":"\u0412\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0439 \u0444\u0430\u0439\u043b %filename \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043d. \u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u0444\u0430\u0439\u043b\u043e\u0432 \u0442\u043e\u043b\u044c\u043a\u043e \u0441\u043e \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u043c\u0438 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u044f\u043c\u0438: %extensions.","Re-order rows by numerical weight instead of dragging.":"\u0423\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0438\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0438 \u043f\u043e \u0432\u0435\u0441\u0443 \u0432\u043c\u0435\u0441\u0442\u043e \u043f\u0435\u0440\u0435\u0442\u0430\u0441\u043a\u0438\u0432\u0430\u043d\u0438\u044f.","Show row weights":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u0432\u0435\u0441 \u0441\u0442\u0440\u043e\u043a","Hide row weights":"\u0421\u043a\u0440\u044b\u0442\u044c \u0432\u0435\u0441 \u0441\u0442\u0440\u043e\u043a","Apply (all displays)":"\u041f\u0440\u0438\u043c\u0435\u043d\u0438\u0442\u044c (\u0432\u0441\u0435 \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u044f)","Apply (this display)":"\u041f\u0440\u0438\u043c\u0435\u043d\u0438\u0442\u044c (\u0434\u0430\u043d\u043d\u043e\u0435 \u043e\u0442\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435)","Revert to default":"\u0412\u0435\u0440\u043d\u0443\u0442\u044c \u043a \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430\u043c \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e","You have unsaved changes":"\u0418\u043c\u0435\u044e\u0442\u0441\u044f \u043d\u0435\u0441\u043e\u0445\u0440\u0430\u043d\u0451\u043d\u043d\u044b\u0435 \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f","Needs to be updated":"\u041d\u0443\u0436\u0434\u0430\u0435\u0442\u0441\u044f \u0432 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0438","Does not need to be updated":"\u041d\u0435 \u043d\u0443\u0436\u0434\u0430\u0435\u0442\u0441\u044f \u0432 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u0438","Show all columns":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u0432\u0441\u0435 \u0441\u0442\u043e\u043b\u0431\u0446\u044b","Show table cells that were hidden to make the table fit within a small screen.":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u044f\u0447\u0435\u0439\u043a\u0438 \u0442\u0430\u0431\u043b\u0438\u0446\u044b, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0431\u044b\u043b\u0438 \u0441\u043a\u0440\u044b\u0442\u044b, \u0447\u0442\u043e\u0431\u044b \u0440\u0430\u0437\u043c\u0435\u0441\u0442\u0438\u0442\u044c \u0432\u0441\u044e \u0442\u0430\u0431\u043b\u0438\u0446\u0443 \u043d\u0430 \u043c\u0430\u043b\u0435\u043d\u044c\u043a\u043e\u043c \u044d\u043a\u0440\u0430\u043d\u0435.","List additional actions":"\u0421\u043f\u0438\u0441\u043e\u043a \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0445 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439","Flag other translations as outdated":"\u041f\u043e\u043c\u0435\u0442\u0438\u0442\u044c \u0434\u0440\u0443\u0433\u0438\u0435 \u043f\u0435\u0440\u0435\u0432\u043e\u0434\u044b \u043a\u0430\u043a \u0443\u0441\u0442\u0430\u0440\u0435\u0432\u0448\u0438\u0435","Do not flag other translations as outdated":"\u041d\u0435 \u043f\u043e\u043c\u0435\u0447\u0430\u0439\u0442\u0435 \u0434\u0440\u0443\u0433\u0438\u0435 \u043f\u0435\u0440\u0435\u0432\u043e\u0434\u044b \u043a\u0430\u043a \u0443\u0441\u0442\u0430\u0440\u0435\u0432\u0448\u0438\u0435","opened":"\u041e\u0442\u043a\u0440\u044b\u0442\u043e","Horizontal orientation":"\u0413\u043e\u0440\u0438\u0437\u043e\u043d\u0442\u0430\u043b\u044c\u043d\u0430\u044f \u043e\u0440\u0438\u0435\u043d\u0442\u0430\u0446\u0438\u044f","Vertical orientation":"\u0412\u0435\u0440\u0442\u0438\u043a\u0430\u043b\u044c\u043d\u0430\u044f \u043e\u0440\u0438\u0435\u043d\u0442\u0430\u0446\u0438\u044f","You have unsaved changes.":"\u0415\u0441\u0442\u044c \u043d\u0435\u0441\u043e\u0445\u0440\u0430\u043d\u0451\u043d\u043d\u044b\u0435 \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f.","@action @title configuration options":"@action @title \u043a\u043e\u043d\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0435 \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438","Tabbing is no longer constrained by the Contextual module.":"\u0418\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0432\u043a\u043b\u0430\u0434\u043e\u043a \u0431\u043e\u043b\u044c\u0448\u0435 \u043d\u0435 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u043e \u043c\u043e\u0434\u0443\u043b\u0435\u043c Context.","Press the esc key to exit.":"\u041d\u0430\u0436\u043c\u0438\u0442\u0435 \u043a\u043d\u043e\u043f\u043a\u0443 ESC \u0434\u043b\u044f \u0432\u044b\u0445\u043e\u0434\u0430.","@count contextual link\u0003@count contextual links":"@count \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u043d\u0430\u044f \u0441\u0441\u044b\u043b\u043a\u0430\u0003@count \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u043d\u044b\u0445 \u0441\u0441\u044b\u043b\u043a\u0438\u0003@count[2] \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u043d\u044b\u0445 \u0441\u0441\u044b\u043b\u043e\u043a","!tour_item of !total":"!tour_item \u0438\u0437 !total","End tour":"\u041a\u043e\u043d\u0435\u0446 \u0442\u0443\u0440\u0430","Discard changes?":"\u041e\u0442\u043c\u0435\u043d\u0438\u0442\u044c \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f?","The toolbar cannot be set to a horizontal orientation when it is locked.":"\u041f\u0430\u043d\u0435\u043b\u044c \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043b\u0435\u043d\u0430 \u0432 \u0433\u043e\u0440\u0438\u0437\u043e\u043d\u0442\u0430\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435 \u043a\u043e\u0433\u0434\u0430 \u043e\u043d\u0430 \u0437\u0430\u0431\u043b\u043e\u043a\u0438\u0440\u043e\u0432\u0430\u043d\u0430.","Changing the text format to %text_format will permanently remove content that is not allowed in that text format.\u003Cbr\u003E\u003Cbr\u003ESave your changes before switching the text format to avoid losing data.":"\u0418\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435 \u0442\u0435\u043a\u0441\u0442\u043e\u0432\u043e\u0433\u043e \u0444\u043e\u0440\u043c\u0430\u0442\u0430 \u043d\u0430 %text_format \u0431\u0435\u0437\u0432\u043e\u0437\u0432\u0440\u0430\u0442\u043d\u043e \u0443\u0434\u0430\u043b\u0438\u0442 \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u043c\u043e\u0435, \u043d\u0435\u0434\u043e\u0441\u0442\u0443\u043f\u043d\u043e\u0435 \u0432 \u043d\u043e\u0432\u043e\u043c \u0442\u0435\u043a\u0441\u0442\u043e\u0432\u043e\u043c \u0444\u043e\u0440\u043c\u0430\u0442\u0435.\u003Cbr\u003E\u003Cbr\u003E\u0414\u043b\u044f \u043f\u0440\u0435\u0434\u043e\u0442\u0432\u0440\u0430\u0449\u0435\u043d\u0438\u044f \u043f\u043e\u0442\u0435\u0440\u0438 \u0434\u0430\u043d\u043d\u044b\u0445 \u0441\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u0435 \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f \u043f\u0435\u0440\u0435\u0434 \u043f\u0435\u0440\u0435\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\u043c \u0444\u043e\u0440\u043c\u0430\u0442\u0430.","Change text format?":"\u0418\u0437\u043c\u0435\u043d\u0438\u0442\u044c \u0444\u043e\u0440\u043c\u0430\u0442 \u0442\u0435\u043a\u0441\u0442\u0430?","Rich Text Editor, !label field":"\u0420\u0435\u0434\u0430\u043a\u0442\u043e\u0440 \u0444\u043e\u0440\u043c\u0430\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u0433\u043e \u0442\u0435\u043a\u0441\u0442\u0430, \u043f\u043e\u043b\u0435 !label","Hide lower priority columns":"\u0421\u043a\u0440\u044b\u0442\u044c \u0441\u0442\u043e\u043b\u0431\u0446\u044b \u0441 \u043d\u0438\u0437\u043a\u0438\u043c \u043f\u0440\u0438\u043e\u0440\u0438\u0442\u0435\u0442\u043e\u043c","!modules modules are available in the modified list.":"\u041c\u043e\u0434\u0443\u043b\u0438 !modules \u0434\u043e\u0441\u0442\u0443\u043f\u043d\u044b \u0432 \u043c\u043e\u0434\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u043e\u043c \u0441\u043f\u0438\u0441\u043a\u0435.","Network problem!":"\u041f\u0440\u043e\u0431\u043b\u0435\u043c\u0430 \u0441 \u0441\u0435\u0442\u044c\u044e!","Authored on @date":"\u0421\u043e\u0437\u0434\u0430\u043d\u043e @date"},"Long month name":{"January":"\u044f\u043d\u0432\u0430\u0440\u044f","February":"\u0444\u0435\u0432\u0440\u0430\u043b\u044f","March":"\u043c\u0430\u0440\u0442\u0430","April":"\u0430\u043f\u0440\u0435\u043b\u044f","May":"\u043c\u0430\u044f","June":"\u0438\u044e\u043d\u044f","July":"\u0438\u044e\u043b\u044f","August":"\u0430\u0432\u0433\u0443\u0441\u0442\u0430","September":"\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044f","October":"\u043e\u043a\u0442\u044f\u0431\u0440\u044f","November":"\u043d\u043e\u044f\u0431\u0440\u044f","December":"\u0434\u0435\u043a\u0430\u0431\u0440\u044f"}},"pluralFormula":{"1":0,"2":1,"3":1,"4":1,"21":0,"22":1,"23":1,"24":1,"31":0,"32":1,"33":1,"34":1,"41":0,"42":1,"43":1,"44":1,"51":0,"52":1,"53":1,"54":1,"61":0,"62":1,"63":1,"64":1,"71":0,"72":1,"73":1,"74":1,"81":0,"82":1,"83":1,"84":1,"91":0,"92":1,"93":1,"94":1,"101":0,"102":1,"103":1,"104":1,"121":0,"122":1,"123":1,"124":1,"131":0,"132":1,"133":1,"134":1,"141":0,"142":1,"143":1,"144":1,"151":0,"152":1,"153":1,"154":1,"161":0,"162":1,"163":1,"164":1,"171":0,"172":1,"173":1,"174":1,"181":0,"182":1,"183":1,"184":1,"191":0,"192":1,"193":1,"194":1,"default":2}};;
/**
* @file
* Defines the Drupal JavaScript API.
*/
/**
* A jQuery object, typically the return value from a `$(selector)` call.
*
* Holds an HTMLElement or a collection of HTMLElements.
*
* @typedef {object} jQuery
*
* @prop {number} length=0
* Number of elements contained in the jQuery object.
*/
/**
* Variable generated by Drupal that holds all translated strings from PHP.
*
* Content of this variable is automatically created by Drupal when using the
* Interface Translation module. It holds the translation of strings used on
* the page.
*
* This variable is used to pass data from the backend to the frontend. Data
* contained in `drupalSettings` is used during behavior initialization.
*
* @global
*
* @var {object} drupalTranslations
*/
/**
* Global Drupal object.
*
* All Drupal JavaScript APIs are contained in this namespace.
*
* @global
*
* @namespace
*/
window.Drupal = {behaviors: {}, locale: {}};
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it in an anonymous closure.
(function (Drupal, drupalSettings, drupalTranslations) {
'use strict';
/**
* Helper to rethrow errors asynchronously.
*
* This way Errors bubbles up outside of the original callstack, making it
* easier to debug errors in the browser.
*
* @param {Error|string} error
* The error to be thrown.
*/
Drupal.throwError = function (error) {
setTimeout(function () { throw error; }, 0);
};
/**
* Custom error thrown after attach/detach if one or more behaviors failed.
* Initializes the JavaScript behaviors for page loads and Ajax requests.
*
* @callback Drupal~behaviorAttach
*
* @param {HTMLDocument|HTMLElement} context
* An element to detach behaviors from.
* @param {?object} settings
* An object containing settings for the current context. It is rarely used.
*
* @see Drupal.attachBehaviors
*/
/**
* Reverts and cleans up JavaScript behavior initialization.
*
* @callback Drupal~behaviorDetach
*
* @param {HTMLDocument|HTMLElement} context
* An element to attach behaviors to.
* @param {object} settings
* An object containing settings for the current context.
* @param {string} trigger
* One of `'unload'`, `'move'`, or `'serialize'`.
*
* @see Drupal.detachBehaviors
*/
/**
* @typedef {object} Drupal~behavior
*
* @prop {Drupal~behaviorAttach} attach
* Function run on page load and after an Ajax call.
* @prop {Drupal~behaviorDetach} detach
* Function run when content is serialized or removed from the page.
*/
/**
* Holds all initialization methods.
*
* @namespace Drupal.behaviors
*
* @type {Object.<string, Drupal~behavior>}
*/
/**
* Defines a behavior to be run during attach and detach phases.
*
* Attaches all registered behaviors to a page element.
*
* Behaviors are event-triggered actions that attach to page elements,
* enhancing default non-JavaScript UIs. Behaviors are registered in the
* {@link Drupal.behaviors} object using the method 'attach' and optionally
* also 'detach'.
*
* {@link Drupal.attachBehaviors} is added below to the `jQuery.ready` event
* and therefore runs on initial page load. Developers implementing Ajax in
* their solutions should also call this function after new page content has
* been loaded, feeding in an element to be processed, in order to attach all
* behaviors to the new content.
*
* Behaviors should use `var elements =
* $(context).find(selector).once('behavior-name');` to ensure the behavior is
* attached only once to a given element. (Doing so enables the reprocessing
* of given elements, which may be needed on occasion despite the ability to
* limit behavior attachment to a particular element.)
*
* @example
* Drupal.behaviors.behaviorName = {
* attach: function (context, settings) {
* // ...
* },
* detach: function (context, settings, trigger) {
* // ...
* }
* };
*
* @param {HTMLDocument|HTMLElement} [context=document]
* An element to attach behaviors to.
* @param {object} [settings=drupalSettings]
* An object containing settings for the current context. If none is given,
* the global {@link drupalSettings} object is used.
*
* @see Drupal~behaviorAttach
* @see Drupal.detachBehaviors
*
* @throws {Drupal~DrupalBehaviorError}
*/
Drupal.attachBehaviors = function (context, settings) {
context = context || document;
settings = settings || drupalSettings;
var behaviors = Drupal.behaviors;
// Execute all of them.
for (var i in behaviors) {
if (behaviors.hasOwnProperty(i) && typeof behaviors[i].attach === 'function') {
// Don't stop the execution of behaviors in case of an error.
try {
behaviors[i].attach(context, settings);
}
catch (e) {
Drupal.throwError(e);
}
}
}
};
/**
* Detaches registered behaviors from a page element.
*
* Developers implementing Ajax in their solutions should call this function
* before page content is about to be removed, feeding in an element to be
* processed, in order to allow special behaviors to detach from the content.
*
* Such implementations should use `.findOnce()` and `.removeOnce()` to find
* elements with their corresponding `Drupal.behaviors.behaviorName.attach`
* implementation, i.e. `.removeOnce('behaviorName')`, to ensure the behavior
* is detached only from previously processed elements.
*
* @param {HTMLDocument|HTMLElement} [context=document]
* An element to detach behaviors from.
* @param {object} [settings=drupalSettings]
* An object containing settings for the current context. If none given,
* the global {@link drupalSettings} object is used.
* @param {string} [trigger='unload']
* A string containing what's causing the behaviors to be detached. The
* possible triggers are:
* - `'unload'`: The context element is being removed from the DOM.
* - `'move'`: The element is about to be moved within the DOM (for example,
* during a tabledrag row swap). After the move is completed,
* {@link Drupal.attachBehaviors} is called, so that the behavior can undo
* whatever it did in response to the move. Many behaviors won't need to
* do anything simply in response to the element being moved, but because
* IFRAME elements reload their "src" when being moved within the DOM,
* behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
* take some action.
* - `'serialize'`: When an Ajax form is submitted, this is called with the
* form as the context. This provides every behavior within the form an
* opportunity to ensure that the field elements have correct content
* in them before the form is serialized. The canonical use-case is so
* that WYSIWYG editors can update the hidden textarea to which they are
* bound.
*
* @throws {Drupal~DrupalBehaviorError}
*
* @see Drupal~behaviorDetach
* @see Drupal.attachBehaviors
*/
Drupal.detachBehaviors = function (context, settings, trigger) {
context = context || document;
settings = settings || drupalSettings;
trigger = trigger || 'unload';
var behaviors = Drupal.behaviors;
// Execute all of them.
for (var i in behaviors) {
if (behaviors.hasOwnProperty(i) && typeof behaviors[i].detach === 'function') {
// Don't stop the execution of behaviors in case of an error.
try {
behaviors[i].detach(context, settings, trigger);
}
catch (e) {
Drupal.throwError(e);
}
}
}
};
/**
* Encodes special characters in a plain-text string for display as HTML.
*
* @param {string} str
* The string to be encoded.
*
* @return {string}
* The encoded string.
*
* @ingroup sanitization
*/
Drupal.checkPlain = function (str) {
str = str.toString()
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
return str;
};
/**
* Replaces placeholders with sanitized values in a string.
*
* @param {string} str
* A string with placeholders.
* @param {object} args
* An object of replacements pairs to make. Incidences of any key in this
* array are replaced with the corresponding value. Based on the first
* character of the key, the value is escaped and/or themed:
* - `'!variable'`: inserted as is.
* - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}).
* - `'%variable'`: escape text and theme as a placeholder for user-
* submitted content ({@link Drupal.checkPlain} +
* `{@link Drupal.theme}('placeholder')`).
*
* @return {string}
* The formatted string.
*
* @see Drupal.t
*/
Drupal.formatString = function (str, args) {
// Keep args intact.
var processedArgs = {};
// Transform arguments before inserting them.
for (var key in args) {
if (args.hasOwnProperty(key)) {
switch (key.charAt(0)) {
// Escaped only.
case '@':
processedArgs[key] = Drupal.checkPlain(args[key]);
break;
// Pass-through.
case '!':
processedArgs[key] = args[key];
break;
// Escaped and placeholder.
default:
processedArgs[key] = Drupal.theme('placeholder', args[key]);
break;
}
}
}
return Drupal.stringReplace(str, processedArgs, null);
};
/**
* Replaces substring.
*
* The longest keys will be tried first. Once a substring has been replaced,
* its new value will not be searched again.
*
* @param {string} str
* A string with placeholders.
* @param {object} args
* Key-value pairs.
* @param {Array|null} keys
* Array of keys from `args`. Internal use only.
*
* @return {string}
* The replaced string.
*/
Drupal.stringReplace = function (str, args, keys) {
if (str.length === 0) {
return str;
}
// If the array of keys is not passed then collect the keys from the args.
if (!Array.isArray(keys)) {
keys = [];
for (var k in args) {
if (args.hasOwnProperty(k)) {
keys.push(k);
}
}
// Order the keys by the character length. The shortest one is the first.
keys.sort(function (a, b) { return a.length - b.length; });
}
if (keys.length === 0) {
return str;
}
// Take next longest one from the end.
var key = keys.pop();
var fragments = str.split(key);
if (keys.length) {
for (var i = 0; i < fragments.length; i++) {
// Process each fragment with a copy of remaining keys.
fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
}
}
return fragments.join(args[key]);
};
/**
* Translates strings to the page language, or a given language.
*
* See the documentation of the server-side t() function for further details.
*
* @param {string} str
* A string containing the English text to translate.
* @param {Object.<string, string>} [args]
* An object of replacements pairs to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* See {@link Drupal.formatString}.
* @param {object} [options]
* Additional options for translation.
* @param {string} [options.context='']
* The context the source string belongs to.
*
* @return {string}
* The formatted string.
* The translated string.
*/
Drupal.t = function (str, args, options) {
options = options || {};
options.context = options.context || '';
// Fetch the localized version of the string.
if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) {
str = drupalTranslations.strings[options.context][str];
}
if (args) {
str = Drupal.formatString(str, args);
}
return str;
};
/**
* Returns the URL to a Drupal page.
*
* @param {string} path
* Drupal path to transform to URL.
*
* @return {string}
* The full URL.
*/
Drupal.url = function (path) {
return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
};
/**
* Returns the passed in URL as an absolute URL.
*
* @param {string} url
* The URL string to be normalized to an absolute URL.
*
* @return {string}
* The normalized, absolute URL.
*
* @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
* @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
* @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
*/
Drupal.url.toAbsolute = function (url) {
var urlParsingNode = document.createElement('a');
// Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
// strings may throw an exception.
try {
url = decodeURIComponent(url);
}
catch (e) {
// Empty.
}
urlParsingNode.setAttribute('href', url);
// IE <= 7 normalizes the URL when assigned to the anchor node similar to
// the other browsers.
return urlParsingNode.cloneNode(false).href;
};
/**
* Returns true if the URL is within Drupal's base path.
*
* @param {string} url
* The URL string to be tested.
*
* @return {bool}
* `true` if local.
*
* @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
*/
Drupal.url.isLocal = function (url) {
// Always use browser-derived absolute URLs in the comparison, to avoid
// attempts to break out of the base path using directory traversal.
var absoluteUrl = Drupal.url.toAbsolute(url);
var protocol = location.protocol;
// Consider URLs that match this site's base URL but use HTTPS instead of HTTP
// as local as well.
if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
protocol = 'https:';
}
var baseUrl = protocol + '//' + location.host + drupalSettings.path.baseUrl.slice(0, -1);
// Decoding non-UTF-8 strings may throw an exception.
try {
absoluteUrl = decodeURIComponent(absoluteUrl);
}
catch (e) {
// Empty.
}
try {
baseUrl = decodeURIComponent(baseUrl);
}
catch (e) {
// Empty.
}
// The given URL matches the site's base URL, or has a path under the site's
// base URL.
return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
};
/**
* Formats a string containing a count of items.
*
* This function ensures that the string is pluralized correctly. Since
* {@link Drupal.t} is called by this function, make sure not to pass
* already-localized strings to it.
*
* See the documentation of the server-side
* \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
* function for more details.
*
* @param {number} count
* The item count to display.
* @param {string} singular
* The string for the singular case. Please make sure it is clear this is
* singular, to ease translation (e.g. use "1 new comment" instead of "1
* new"). Do not use @count in the singular string.
* @param {string} plural
* The string for the plural case. Please make sure it is clear this is
* plural, to ease translation. Use @count in place of the item count, as in
* "@count new comments".
* @param {object} [args]
* An object of replacements pairs to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* See {@link Drupal.formatString}.
* Note that you do not need to include @count in this array.
* This replacement is done automatically for the plural case.
* @param {object} [options]
* The options to pass to the {@link Drupal.t} function.
*
* @return {string}
* A translated string.
*/
Drupal.formatPlural = function (count, singular, plural, args, options) {
args = args || {};
args['@count'] = count;
var pluralDelimiter = drupalSettings.pluralDelimiter;
var translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
var index = 0;
// Determine the index of the plural form.
if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) {
index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula['default'];
}
else if (args['@count'] !== 1) {
index = 1;
}
return translations[index];
};
/**
* Encodes a Drupal path for use in a URL.
*
* For aesthetic reasons slashes are not escaped.
*
* @param {string} item
* Unencoded path.
*
* @return {string}
* The encoded path.
*/
Drupal.encodePath = function (item) {
return window.encodeURIComponent(item).replace(/%2F/g, '/');
};
/**
* Generates the themed representation of a Drupal object.
*
* All requests for themed output must go through this function. It examines
* the request and routes it to the appropriate theme function. If the current
* theme does not provide an override function, the generic theme function is
* called.
*
* @example
* <caption>To retrieve the HTML for text that should be emphasized and
* displayed as a placeholder inside a sentence.</caption>
* Drupal.theme('placeholder', text);
*
* @namespace
*
* @param {function} func
* The name of the theme function to call.
* @param {...args}
* Additional arguments to pass along to the theme function.
*
* @return {string|object|HTMLElement|jQuery}
* Any data the theme function returns. This could be a plain HTML string,
* but also a complex object.
*/
Drupal.theme = function (func) {
var args = Array.prototype.slice.apply(arguments, [1]);
if (func in Drupal.theme) {
return Drupal.theme[func].apply(this, args);
}
};
/**
* Formats text for emphasized display in a placeholder inside a sentence.
*
* @param {string} str
* The text to format (plain-text).
*
* @return {string}
* The formatted text (html).
*/
Drupal.theme.placeholder = function (str) {
return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
};
})(Drupal, window.drupalSettings, window.drupalTranslations);
;
// Allow other JavaScript libraries to use $.
if (window.jQuery) {
jQuery.noConflict();
}
// Class indicating that JS is enabled; used for styling purpose.
document.documentElement.className += ' js';
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it in an anonymous closure.
(function (domready, Drupal, drupalSettings) {
'use strict';
// Attach all behaviors.
domready(function () { Drupal.attachBehaviors(document, drupalSettings); });
})(domready, Drupal, window.drupalSettings);
;
/*!
* jQuery UI Core 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,r){var i,s,o,u=t.nodeName.toLowerCase();return"area"===u?(i=t.parentNode,s=i.name,!t.href||!s||i.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap='#"+s+"']")[0],!!o&&n(o))):(/^(input|select|textarea|button|object)$/.test(u)?!t.disabled:"a"===u?t.href||r:r)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return e.css(this,"visibility")==="hidden"}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var n=this.css("position"),r=n==="absolute",i=t?/(auto|scroll|hidden)/:/(auto|scroll)/,s=this.parents().filter(function(){var t=e(this);return r&&t.css("position")==="static"?!1:i.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return n==="fixed"||!s.length?e(this[0].ownerDocument||document):s},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(n){return t(n,!isNaN(e.attr(n,"tabindex")))},tabbable:function(n){var r=e.attr(n,"tabindex"),i=isNaN(r);return(i||r>=0)&&t(n,!i)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,n){function o(t,n,i,s){return e.each(r,function(){n-=parseFloat(e.css(t,"padding"+this))||0,i&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var r=n==="Width"?["Left","Right"]:["Top","Bottom"],i=n.toLowerCase(),s={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(t){return t===undefined?s["inner"+n].call(this):this.each(function(){e(this).css(i,o(this,t)+"px")})},e.fn["outer"+n]=function(t,r){return typeof t!="number"?s["outer"+n].call(this,t):this.each(function(){e(this).css(i,o(this,t,!0,r)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(n,r){return typeof n=="number"?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(t!==undefined)return this.css("zIndex",t);if(this.length){var n=e(this[0]),r,i;while(n.length&&n[0]!==document){r=n.css("position");if(r==="absolute"||r==="relative"||r==="fixed"){i=parseInt(n.css("zIndex"),10);if(!isNaN(i)&&i!==0)return i}n=n.parent()}}return 0}}),e.ui.plugin={add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n,r){var i,s=e.plugins[t];if(!s)return;if(!r&&(!e.element[0].parentNode||e.element[0].parentNode.nodeType===11))return;for(i=0;i<s.length;i++)e.options[s[i][0]]&&s[i][1].apply(e.element,n)}}});;
/**
* @file
* Attaches behaviors for the Contextual module.
*/
(function ($, Drupal, drupalSettings, _, Backbone, JSON, storage) {
'use strict';
var options = $.extend(drupalSettings.contextual,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
open: Drupal.t('Open'),
close: Drupal.t('Close')
}
}
);
// Clear the cached contextual links whenever the current user's set of
// permissions changes.
var cachedPermissionsHash = storage.getItem('Drupal.contextual.permissionsHash');
var permissionsHash = drupalSettings.user.permissionsHash;
if (cachedPermissionsHash !== permissionsHash) {
if (typeof permissionsHash === 'string') {
_.chain(storage).keys().each(function (key) {
if (key.substring(0, 18) === 'Drupal.contextual.') {
storage.removeItem(key);
}
});
}
storage.setItem('Drupal.contextual.permissionsHash', permissionsHash);
}
/**
* Initializes a contextual link: updates its DOM, sets up model and views.
*
* @param {jQuery} $contextual
* A contextual links placeholder DOM element, containing the actual
* contextual links as rendered by the server.
* @param {string} html
* The server-side rendered HTML for this contextual link.
*/
function initContextual($contextual, html) {
var $region = $contextual.closest('.contextual-region');
var contextual = Drupal.contextual;
$contextual
// Update the placeholder to contain its rendered contextual links.
.html(html)
// Use the placeholder as a wrapper with a specific class to provide
// positioning and behavior attachment context.
.addClass('contextual')
// Ensure a trigger element exists before the actual contextual links.
.prepend(Drupal.theme('contextualTrigger'));
// Set the destination parameter on each of the contextual links.
var destination = 'destination=' + Drupal.encodePath(drupalSettings.path.currentPath);
$contextual.find('.contextual-links a').each(function () {
var url = this.getAttribute('href');
var glue = (url.indexOf('?') === -1) ? '?' : '&';
this.setAttribute('href', url + glue + destination);
});
// Create a model and the appropriate views.
var model = new contextual.StateModel({
title: $region.find('h2').eq(0).text().trim()
});
var viewOptions = $.extend({el: $contextual, model: model}, options);
contextual.views.push({
visual: new contextual.VisualView(viewOptions),
aural: new contextual.AuralView(viewOptions),
keyboard: new contextual.KeyboardView(viewOptions)
});
contextual.regionViews.push(new contextual.RegionView(
$.extend({el: $region, model: model}, options))
);
// Add the model to the collection. This must happen after the views have
// been associated with it, otherwise collection change event handlers can't
// trigger the model change event handler in its views.
contextual.collection.add(model);
// Let other JavaScript react to the adding of a new contextual link.
$(document).trigger('drupalContextualLinkAdded', {
$el: $contextual,
$region: $region,
model: model
});
// Fix visual collisions between contextual link triggers.
adjustIfNestedAndOverlapping($contextual);
}
/**
* Determines if a contextual link is nested & overlapping, if so: adjusts it.
*
* This only deals with two levels of nesting; deeper levels are not touched.
*
* @param {jQuery} $contextual
* A contextual links placeholder DOM element, containing the actual
* contextual links as rendered by the server.
*/
function adjustIfNestedAndOverlapping($contextual) {
var $contextuals = $contextual
// @todo confirm that .closest() is not sufficient
.parents('.contextual-region').eq(-1)
.find('.contextual');
// Early-return when there's no nesting.
if ($contextuals.length === 1) {
return;
}
// If the two contextual links overlap, then we move the second one.
var firstTop = $contextuals.eq(0).offset().top;
var secondTop = $contextuals.eq(1).offset().top;
if (firstTop === secondTop) {
var $nestedContextual = $contextuals.eq(1);
// Retrieve height of nested contextual link.
var height = 0;
var $trigger = $nestedContextual.find('.trigger');
// Elements with the .visually-hidden class have no dimensions, so this
// class must be temporarily removed to the calculate the height.
$trigger.removeClass('visually-hidden');
height = $nestedContextual.height();
$trigger.addClass('visually-hidden');
// Adjust nested contextual link's position.
$nestedContextual.css({top: $nestedContextual.position().top + height});
}
}
/**
* Attaches outline behavior for regions associated with contextual links.
*
* Events
* Contextual triggers an event that can be used by other scripts.
* - drupalContextualLinkAdded: Triggered when a contextual link is added.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the outline behavior to the right context.
*/
Drupal.behaviors.contextual = {
attach: function (context) {
var $context = $(context);
// Find all contextual links placeholders, if any.
var $placeholders = $context.find('[data-contextual-id]').once('contextual-render');
if ($placeholders.length === 0) {
return;
}
// Collect the IDs for all contextual links placeholders.
var ids = [];
$placeholders.each(function () {
ids.push($(this).attr('data-contextual-id'));
});
// Update all contextual links placeholders whose HTML is cached.
var uncachedIDs = _.filter(ids, function initIfCached(contextualID) {
var html = storage.getItem('Drupal.contextual.' + contextualID);
if (html && html.length) {
// Initialize after the current execution cycle, to make the AJAX
// request for retrieving the uncached contextual links as soon as
// possible, but also to ensure that other Drupal behaviors have had
// the chance to set up an event listener on the Backbone collection
// Drupal.contextual.collection.
window.setTimeout(function () {
initContextual($context.find('[data-contextual-id="' + contextualID + '"]'), html);
});
return false;
}
return true;
});
// Perform an AJAX request to let the server render the contextual links
// for each of the placeholders.
if (uncachedIDs.length > 0) {
$.ajax({
url: Drupal.url('contextual/render'),
type: 'POST',
data: {'ids[]': uncachedIDs},
dataType: 'json',
success: function (results) {
_.each(results, function (html, contextualID) {
// Store the metadata.
storage.setItem('Drupal.contextual.' + contextualID, html);
// If the rendered contextual links are empty, then the current
// user does not have permission to access the associated links:
// don't render anything.
if (html.length > 0) {
// Update the placeholders to contain its rendered contextual
// links. Usually there will only be one placeholder, but it's
// possible for multiple identical placeholders exist on the
// page (probably because the same content appears more than
// once).
$placeholders = $context.find('[data-contextual-id="' + contextualID + '"]');
// Initialize the contextual links.
for (var i = 0; i < $placeholders.length; i++) {
initContextual($placeholders.eq(i), html);
}
}
});
}
});
}
}
};
/**
* Namespace for contextual related functionality.
*
* @namespace
*/
Drupal.contextual = {
/**
* The {@link Drupal.contextual.View} instances associated with each list
* element of contextual links.
*
* @type {Array}
*/
views: [],
/**
* The {@link Drupal.contextual.RegionView} instances associated with each
* contextual region element.
*
* @type {Array}
*/
regionViews: []
};
/**
* A Backbone.Collection of {@link Drupal.contextual.StateModel} instances.
*
* @type {Backbone.Collection}
*/
Drupal.contextual.collection = new Backbone.Collection([], {model: Drupal.contextual.StateModel});
/**
* A trigger is an interactive element often bound to a click handler.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.contextualTrigger = function () {
return '<button class="trigger visually-hidden focusable" type="button"></button>';
};
})(jQuery, Drupal, drupalSettings, _, Backbone, window.JSON, window.sessionStorage);
;
/**
* @file
* A Backbone Model for the state of a contextual link's trigger, list & region.
*/
(function (Drupal, Backbone) {
'use strict';
/**
* Models the state of a contextual link's trigger, list & region.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.contextual.StateModel = Backbone.Model.extend(/** @lends Drupal.contextual.StateModel# */{
/**
* @type {object}
*
* @prop {string} title
* @prop {bool} regionIsHovered
* @prop {bool} hasFocus
* @prop {bool} isOpen
* @prop {bool} isLocked
*/
defaults: /** @lends Drupal.contextual.StateModel# */{
/**
* The title of the entity to which these contextual links apply.
*
* @type {string}
*/
title: '',
/**
* Represents if the contextual region is being hovered.
*
* @type {bool}
*/
regionIsHovered: false,
/**
* Represents if the contextual trigger or options have focus.
*
* @type {bool}
*/
hasFocus: false,
/**
* Represents if the contextual options for an entity are available to
* be selected (i.e. whether the list of options is visible).
*
* @type {bool}
*/
isOpen: false,
/**
* When the model is locked, the trigger remains active.
*
* @type {bool}
*/
isLocked: false
},
/**
* Opens or closes the contextual link.
*
* If it is opened, then also give focus.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
toggleOpen: function () {
var newIsOpen = !this.get('isOpen');
this.set('isOpen', newIsOpen);
if (newIsOpen) {
this.focus();
}
return this;
},
/**
* Closes this contextual link.
*
* Does not call blur() because we want to allow a contextual link to have
* focus, yet be closed for example when hovering.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
close: function () {
this.set('isOpen', false);
return this;
},
/**
* Gives focus to this contextual link.
*
* Also closes + removes focus from every other contextual link.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
focus: function () {
this.set('hasFocus', true);
var cid = this.cid;
this.collection.each(function (model) {
if (model.cid !== cid) {
model.close().blur();
}
});
return this;
},
/**
* Removes focus from this contextual link, unless it is open.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
blur: function () {
if (!this.get('isOpen')) {
this.set('hasFocus', false);
}
return this;
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides the aural view of a contextual link.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextual.AuralView = Backbone.View.extend(/** @lends Drupal.contextual.AuralView# */{
/**
* Renders the aural view of a contextual link (i.e. screen reader support).
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
*/
initialize: function (options) {
this.options = options;
this.listenTo(this.model, 'change', this.render);
// Use aria-role form so that the number of items in the list is spoken.
this.$el.attr('role', 'form');
// Initial render.
this.render();
},
/**
* @inheritdoc
*/
render: function () {
var isOpen = this.model.get('isOpen');
// Set the hidden property of the links.
this.$el.find('.contextual-links')
.prop('hidden', !isOpen);
// Update the view of the trigger.
this.$el.find('.trigger')
.text(Drupal.t('@action @title configuration options', {
'@action': (!isOpen) ? this.options.strings.open : this.options.strings.close,
'@title': this.model.get('title')
}))
.attr('aria-pressed', isOpen);
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides keyboard interaction for a contextual link.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextual.KeyboardView = Backbone.View.extend(/** @lends Drupal.contextual.KeyboardView# */{
/**
* @type {object}
*/
events: {
'focus .trigger': 'focus',
'focus .contextual-links a': 'focus',
'blur .trigger': function () { this.model.blur(); },
'blur .contextual-links a': function () {
// Set up a timeout to allow a user to tab between the trigger and the
// contextual links without the menu dismissing.
var that = this;
this.timer = window.setTimeout(function () {
that.model.close().blur();
}, 150);
}
},
/**
* Provides keyboard interaction for a contextual link.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
/**
* The timer is used to create a delay before dismissing the contextual
* links on blur. This is only necessary when keyboard users tab into
* contextual links without edit mode (i.e. without TabbingManager).
* That means that if we decide to disable tabbing of contextual links
* without edit mode, all this timer logic can go away.
*
* @type {NaN|number}
*/
this.timer = NaN;
},
/**
* Sets focus on the model; Clears the timer that dismisses the links.
*/
focus: function () {
// Clear the timeout that might have been set by blurring a link.
window.clearTimeout(this.timer);
this.model.focus();
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that renders the visual view of a contextual region element.
*/
(function (Drupal, Backbone, Modernizr) {
'use strict';
Drupal.contextual.RegionView = Backbone.View.extend(/** @lends Drupal.contextual.RegionView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
var mapping = {
mouseenter: function () { this.model.set('regionIsHovered', true); },
mouseleave: function () {
this.model.close().blur().set('regionIsHovered', false);
}
};
// We don't want mouse hover events on touch.
if (Modernizr.touchevents) {
mapping = {};
}
return mapping;
},
/**
* Renders the visual view of a contextual region element.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:hasFocus', this.render);
},
/**
* @inheritdoc
*
* @return {Drupal.contextual.RegionView}
* The current contextual region view.
*/
render: function () {
this.$el.toggleClass('focus', this.model.get('hasFocus'));
return this;
}
});
})(Drupal, Backbone, Modernizr);
;
/**
* @file
* A Backbone View that provides the visual view of a contextual link.
*/
(function (Drupal, Backbone, Modernizr) {
'use strict';
Drupal.contextual.VisualView = Backbone.View.extend(/** @lends Drupal.contextual.VisualView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
var mapping = {
'click .trigger': function () { this.model.toggleOpen(); },
'touchend .trigger': touchEndToClick,
'click .contextual-links a': function () { this.model.close().blur(); },
'touchend .contextual-links a': touchEndToClick
};
// We only want mouse hover events on non-touch.
if (!Modernizr.touchevents) {
mapping.mouseenter = function () { this.model.focus(); };
}
return mapping;
},
/**
* Renders the visual view of a contextual link. Listens to mouse & touch.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
/**
* @inheritdoc
*
* @return {Drupal.contextual.VisualView}
* The current contextual visual view.
*/
render: function () {
var isOpen = this.model.get('isOpen');
// The trigger should be visible when:
// - the mouse hovered over the region,
// - the trigger is locked,
// - and for as long as the contextual menu is open.
var isVisible = this.model.get('isLocked') || this.model.get('regionIsHovered') || isOpen;
this.$el
// The open state determines if the links are visible.
.toggleClass('open', isOpen)
// Update the visibility of the trigger.
.find('.trigger').toggleClass('visually-hidden', !isVisible);
// Nested contextual region handling: hide any nested contextual triggers.
if ('isOpen' in this.model.changed) {
this.$el.closest('.contextual-region')
.find('.contextual .trigger:not(:first)')
.toggle(!isOpen);
}
return this;
}
});
})(Drupal, Backbone, Modernizr);
;
/*!
* jQuery Form Plugin
* version: 3.51.0-2014.06.20
* Requires jQuery v1.5 or later
* Copyright (c) 2014 M. Alsup
* Examples and documentation at: http://malsup.com/jquery/form/
* Project repository: https://github.com/malsup/form
* Dual licensed under the MIT and GPL licenses.
* https://github.com/malsup/form#copyright-and-license
*/
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):e("undefined"!=typeof jQuery?jQuery:window.Zepto)}(function(e){"use strict";function t(t){var r=t.data;t.isDefaultPrevented()||(t.preventDefault(),e(t.target).ajaxSubmit(r))}function r(t){var r=t.target,a=e(r);if(!a.is("[type=submit],[type=image]")){var n=a.closest("[type=submit]");if(0===n.length)return;r=n[0]}var i=this;if(i.clk=r,"image"==r.type)if(void 0!==t.offsetX)i.clk_x=t.offsetX,i.clk_y=t.offsetY;else if("function"==typeof e.fn.offset){var o=a.offset();i.clk_x=t.pageX-o.left,i.clk_y=t.pageY-o.top}else i.clk_x=t.pageX-r.offsetLeft,i.clk_y=t.pageY-r.offsetTop;setTimeout(function(){i.clk=i.clk_x=i.clk_y=null},100)}function a(){if(e.fn.ajaxSubmit.debug){var t="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(t):window.opera&&window.opera.postError&&window.opera.postError(t)}}var n={};n.fileapi=void 0!==e("<input type='file'/>").get(0).files,n.formdata=void 0!==window.FormData;var i=!!e.fn.prop;e.fn.attr2=function(){if(!i)return this.attr.apply(this,arguments);var e=this.prop.apply(this,arguments);return e&&e.jquery||"string"==typeof e?e:this.attr.apply(this,arguments)},e.fn.ajaxSubmit=function(t){function r(r){var a,n,i=e.param(r,t.traditional).split("&"),o=i.length,s=[];for(a=0;o>a;a++)i[a]=i[a].replace(/\+/g," "),n=i[a].split("="),s.push([decodeURIComponent(n[0]),decodeURIComponent(n[1])]);return s}function o(a){for(var n=new FormData,i=0;i<a.length;i++)n.append(a[i].name,a[i].value);if(t.extraData){var o=r(t.extraData);for(i=0;i<o.length;i++)o[i]&&n.append(o[i][0],o[i][1])}t.data=null;var s=e.extend(!0,{},e.ajaxSettings,t,{contentType:!1,processData:!1,cache:!1,type:u||"POST"});t.uploadProgress&&(s.xhr=function(){var r=e.ajaxSettings.xhr();return r.upload&&r.upload.addEventListener("progress",function(e){var r=0,a=e.loaded||e.position,n=e.total;e.lengthComputable&&(r=Math.ceil(a/n*100)),t.uploadProgress(e,a,n,r)},!1),r}),s.data=null;var c=s.beforeSend;return s.beforeSend=function(e,r){r.data=t.formData?t.formData:n,c&&c.call(this,e,r)},e.ajax(s)}function s(r){function n(e){var t=null;try{e.contentWindow&&(t=e.contentWindow.document)}catch(r){a("cannot get iframe.contentWindow document: "+r)}if(t)return t;try{t=e.contentDocument?e.contentDocument:e.document}catch(r){a("cannot get iframe.contentDocument: "+r),t=e.document}return t}function o(){function t(){try{var e=n(g).readyState;a("state = "+e),e&&"uninitialized"==e.toLowerCase()&&setTimeout(t,50)}catch(r){a("Server abort: ",r," (",r.name,")"),s(k),j&&clearTimeout(j),j=void 0}}var r=f.attr2("target"),i=f.attr2("action"),o="multipart/form-data",c=f.attr("enctype")||f.attr("encoding")||o;w.setAttribute("target",p),(!u||/post/i.test(u))&&w.setAttribute("method","POST"),i!=m.url&&w.setAttribute("action",m.url),m.skipEncodingOverride||u&&!/post/i.test(u)||f.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"}),m.timeout&&(j=setTimeout(function(){T=!0,s(D)},m.timeout));var l=[];try{if(m.extraData)for(var d in m.extraData)m.extraData.hasOwnProperty(d)&&l.push(e.isPlainObject(m.extraData[d])&&m.extraData[d].hasOwnProperty("name")&&m.extraData[d].hasOwnProperty("value")?e('<input type="hidden" name="'+m.extraData[d].name+'">').val(m.extraData[d].value).appendTo(w)[0]:e('<input type="hidden" name="'+d+'">').val(m.extraData[d]).appendTo(w)[0]);m.iframeTarget||v.appendTo("body"),g.attachEvent?g.attachEvent("onload",s):g.addEventListener("load",s,!1),setTimeout(t,15);try{w.submit()}catch(h){var x=document.createElement("form").submit;x.apply(w)}}finally{w.setAttribute("action",i),w.setAttribute("enctype",c),r?w.setAttribute("target",r):f.removeAttr("target"),e(l).remove()}}function s(t){if(!x.aborted&&!F){if(M=n(g),M||(a("cannot access response document"),t=k),t===D&&x)return x.abort("timeout"),void S.reject(x,"timeout");if(t==k&&x)return x.abort("server abort"),void S.reject(x,"error","server abort");if(M&&M.location.href!=m.iframeSrc||T){g.detachEvent?g.detachEvent("onload",s):g.removeEventListener("load",s,!1);var r,i="success";try{if(T)throw"timeout";var o="xml"==m.dataType||M.XMLDocument||e.isXMLDoc(M);if(a("isXml="+o),!o&&window.opera&&(null===M.body||!M.body.innerHTML)&&--O)return a("requeing onLoad callback, DOM not available"),void setTimeout(s,250);var u=M.body?M.body:M.documentElement;x.responseText=u?u.innerHTML:null,x.responseXML=M.XMLDocument?M.XMLDocument:M,o&&(m.dataType="xml"),x.getResponseHeader=function(e){var t={"content-type":m.dataType};return t[e.toLowerCase()]},u&&(x.status=Number(u.getAttribute("status"))||x.status,x.statusText=u.getAttribute("statusText")||x.statusText);var c=(m.dataType||"").toLowerCase(),l=/(json|script|text)/.test(c);if(l||m.textarea){var f=M.getElementsByTagName("textarea")[0];if(f)x.responseText=f.value,x.status=Number(f.getAttribute("status"))||x.status,x.statusText=f.getAttribute("statusText")||x.statusText;else if(l){var p=M.getElementsByTagName("pre")[0],h=M.getElementsByTagName("body")[0];p?x.responseText=p.textContent?p.textContent:p.innerText:h&&(x.responseText=h.textContent?h.textContent:h.innerText)}}else"xml"==c&&!x.responseXML&&x.responseText&&(x.responseXML=X(x.responseText));try{E=_(x,c,m)}catch(y){i="parsererror",x.error=r=y||i}}catch(y){a("error caught: ",y),i="error",x.error=r=y||i}x.aborted&&(a("upload aborted"),i=null),x.status&&(i=x.status>=200&&x.status<300||304===x.status?"success":"error"),"success"===i?(m.success&&m.success.call(m.context,E,"success",x),S.resolve(x.responseText,"success",x),d&&e.event.trigger("ajaxSuccess",[x,m])):i&&(void 0===r&&(r=x.statusText),m.error&&m.error.call(m.context,x,i,r),S.reject(x,"error",r),d&&e.event.trigger("ajaxError",[x,m,r])),d&&e.event.trigger("ajaxComplete",[x,m]),d&&!--e.active&&e.event.trigger("ajaxStop"),m.complete&&m.complete.call(m.context,x,i),F=!0,m.timeout&&clearTimeout(j),setTimeout(function(){m.iframeTarget?v.attr("src",m.iframeSrc):v.remove(),x.responseXML=null},100)}}}var c,l,m,d,p,v,g,x,y,b,T,j,w=f[0],S=e.Deferred();if(S.abort=function(e){x.abort(e)},r)for(l=0;l<h.length;l++)c=e(h[l]),i?c.prop("disabled",!1):c.removeAttr("disabled");if(m=e.extend(!0,{},e.ajaxSettings,t),m.context=m.context||m,p="jqFormIO"+(new Date).getTime(),m.iframeTarget?(v=e(m.iframeTarget),b=v.attr2("name"),b?p=b:v.attr2("name",p)):(v=e('<iframe name="'+p+'" src="'+m.iframeSrc+'" />'),v.css({position:"absolute",top:"-1000px",left:"-1000px"})),g=v[0],x={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(t){var r="timeout"===t?"timeout":"aborted";a("aborting upload... "+r),this.aborted=1;try{g.contentWindow.document.execCommand&&g.contentWindow.document.execCommand("Stop")}catch(n){}v.attr("src",m.iframeSrc),x.error=r,m.error&&m.error.call(m.context,x,r,t),d&&e.event.trigger("ajaxError",[x,m,r]),m.complete&&m.complete.call(m.context,x,r)}},d=m.global,d&&0===e.active++&&e.event.trigger("ajaxStart"),d&&e.event.trigger("ajaxSend",[x,m]),m.beforeSend&&m.beforeSend.call(m.context,x,m)===!1)return m.global&&e.active--,S.reject(),S;if(x.aborted)return S.reject(),S;y=w.clk,y&&(b=y.name,b&&!y.disabled&&(m.extraData=m.extraData||{},m.extraData[b]=y.value,"image"==y.type&&(m.extraData[b+".x"]=w.clk_x,m.extraData[b+".y"]=w.clk_y)));var D=1,k=2,A=e("meta[name=csrf-token]").attr("content"),L=e("meta[name=csrf-param]").attr("content");L&&A&&(m.extraData=m.extraData||{},m.extraData[L]=A),m.forceSync?o():setTimeout(o,10);var E,M,F,O=50,X=e.parseXML||function(e,t){return window.ActiveXObject?(t=new ActiveXObject("Microsoft.XMLDOM"),t.async="false",t.loadXML(e)):t=(new DOMParser).parseFromString(e,"text/xml"),t&&t.documentElement&&"parsererror"!=t.documentElement.nodeName?t:null},C=e.parseJSON||function(e){return window.eval("("+e+")")},_=function(t,r,a){var n=t.getResponseHeader("content-type")||"",i="xml"===r||!r&&n.indexOf("xml")>=0,o=i?t.responseXML:t.responseText;return i&&"parsererror"===o.documentElement.nodeName&&e.error&&e.error("parsererror"),a&&a.dataFilter&&(o=a.dataFilter(o,r)),"string"==typeof o&&("json"===r||!r&&n.indexOf("json")>=0?o=C(o):("script"===r||!r&&n.indexOf("javascript")>=0)&&e.globalEval(o)),o};return S}if(!this.length)return a("ajaxSubmit: skipping submit process - no element selected"),this;var u,c,l,f=this;"function"==typeof t?t={success:t}:void 0===t&&(t={}),u=t.type||this.attr2("method"),c=t.url||this.attr2("action"),l="string"==typeof c?e.trim(c):"",l=l||window.location.href||"",l&&(l=(l.match(/^([^#]+)/)||[])[1]),t=e.extend(!0,{url:l,success:e.ajaxSettings.success,type:u||e.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},t);var m={};if(this.trigger("form-pre-serialize",[this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(t.beforeSerialize&&t.beforeSerialize(this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSerialize callback"),this;var d=t.traditional;void 0===d&&(d=e.ajaxSettings.traditional);var p,h=[],v=this.formToArray(t.semantic,h);if(t.data&&(t.extraData=t.data,p=e.param(t.data,d)),t.beforeSubmit&&t.beforeSubmit(v,this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSubmit callback"),this;if(this.trigger("form-submit-validate",[v,this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;var g=e.param(v,d);p&&(g=g?g+"&"+p:p),"GET"==t.type.toUpperCase()?(t.url+=(t.url.indexOf("?")>=0?"&":"?")+g,t.data=null):t.data=g;var x=[];if(t.resetForm&&x.push(function(){f.resetForm()}),t.clearForm&&x.push(function(){f.clearForm(t.includeHidden)}),!t.dataType&&t.target){var y=t.success||function(){};x.push(function(r){var a=t.replaceTarget?"replaceWith":"html";e(t.target)[a](r).each(y,arguments)})}else t.success&&x.push(t.success);if(t.success=function(e,r,a){for(var n=t.context||this,i=0,o=x.length;o>i;i++)x[i].apply(n,[e,r,a||f,f])},t.error){var b=t.error;t.error=function(e,r,a){var n=t.context||this;b.apply(n,[e,r,a,f])}}if(t.complete){var T=t.complete;t.complete=function(e,r){var a=t.context||this;T.apply(a,[e,r,f])}}var j=e("input[type=file]:enabled",this).filter(function(){return""!==e(this).val()}),w=j.length>0,S="multipart/form-data",D=f.attr("enctype")==S||f.attr("encoding")==S,k=n.fileapi&&n.formdata;a("fileAPI :"+k);var A,L=(w||D)&&!k;t.iframe!==!1&&(t.iframe||L)?t.closeKeepAlive?e.get(t.closeKeepAlive,function(){A=s(v)}):A=s(v):A=(w||D)&&k?o(v):e.ajax(t),f.removeData("jqxhr").data("jqxhr",A);for(var E=0;E<h.length;E++)h[E]=null;return this.trigger("form-submit-notify",[this,t]),this},e.fn.ajaxForm=function(n){if(n=n||{},n.delegation=n.delegation&&e.isFunction(e.fn.on),!n.delegation&&0===this.length){var i={s:this.selector,c:this.context};return!e.isReady&&i.s?(a("DOM not ready, queuing ajaxForm"),e(function(){e(i.s,i.c).ajaxForm(n)}),this):(a("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)")),this)}return n.delegation?(e(document).off("submit.form-plugin",this.selector,t).off("click.form-plugin",this.selector,r).on("submit.form-plugin",this.selector,n,t).on("click.form-plugin",this.selector,n,r),this):this.ajaxFormUnbind().bind("submit.form-plugin",n,t).bind("click.form-plugin",n,r)},e.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")},e.fn.formToArray=function(t,r){var a=[];if(0===this.length)return a;var i,o=this[0],s=this.attr("id"),u=t?o.getElementsByTagName("*"):o.elements;if(u&&!/MSIE [678]/.test(navigator.userAgent)&&(u=e(u).get()),s&&(i=e(':input[form="'+s+'"]').get(),i.length&&(u=(u||[]).concat(i))),!u||!u.length)return a;var c,l,f,m,d,p,h;for(c=0,p=u.length;p>c;c++)if(d=u[c],f=d.name,f&&!d.disabled)if(t&&o.clk&&"image"==d.type)o.clk==d&&(a.push({name:f,value:e(d).val(),type:d.type}),a.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}));else if(m=e.fieldValue(d,!0),m&&m.constructor==Array)for(r&&r.push(d),l=0,h=m.length;h>l;l++)a.push({name:f,value:m[l]});else if(n.fileapi&&"file"==d.type){r&&r.push(d);var v=d.files;if(v.length)for(l=0;l<v.length;l++)a.push({name:f,value:v[l],type:d.type});else a.push({name:f,value:"",type:d.type})}else null!==m&&"undefined"!=typeof m&&(r&&r.push(d),a.push({name:f,value:m,type:d.type,required:d.required}));if(!t&&o.clk){var g=e(o.clk),x=g[0];f=x.name,f&&!x.disabled&&"image"==x.type&&(a.push({name:f,value:g.val()}),a.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}))}return a},e.fn.formSerialize=function(t){return e.param(this.formToArray(t))},e.fn.fieldSerialize=function(t){var r=[];return this.each(function(){var a=this.name;if(a){var n=e.fieldValue(this,t);if(n&&n.constructor==Array)for(var i=0,o=n.length;o>i;i++)r.push({name:a,value:n[i]});else null!==n&&"undefined"!=typeof n&&r.push({name:this.name,value:n})}}),e.param(r)},e.fn.fieldValue=function(t){for(var r=[],a=0,n=this.length;n>a;a++){var i=this[a],o=e.fieldValue(i,t);null===o||"undefined"==typeof o||o.constructor==Array&&!o.length||(o.constructor==Array?e.merge(r,o):r.push(o))}return r},e.fieldValue=function(t,r){var a=t.name,n=t.type,i=t.tagName.toLowerCase();if(void 0===r&&(r=!0),r&&(!a||t.disabled||"reset"==n||"button"==n||("checkbox"==n||"radio"==n)&&!t.checked||("submit"==n||"image"==n)&&t.form&&t.form.clk!=t||"select"==i&&-1==t.selectedIndex))return null;if("select"==i){var o=t.selectedIndex;if(0>o)return null;for(var s=[],u=t.options,c="select-one"==n,l=c?o+1:u.length,f=c?o:0;l>f;f++){var m=u[f];if(m.selected){var d=m.value;if(d||(d=m.attributes&&m.attributes.value&&!m.attributes.value.specified?m.text:m.value),c)return d;s.push(d)}}return s}return e(t).val()},e.fn.clearForm=function(t){return this.each(function(){e("input,select,textarea",this).clearFields(t)})},e.fn.clearFields=e.fn.clearInputs=function(t){var r=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var a=this.type,n=this.tagName.toLowerCase();r.test(a)||"textarea"==n?this.value="":"checkbox"==a||"radio"==a?this.checked=!1:"select"==n?this.selectedIndex=-1:"file"==a?/MSIE/.test(navigator.userAgent)?e(this).replaceWith(e(this).clone(!0)):e(this).val(""):t&&(t===!0&&/hidden/.test(a)||"string"==typeof t&&e(this).is(t))&&(this.value="")})},e.fn.resetForm=function(){return this.each(function(){("function"==typeof this.reset||"object"==typeof this.reset&&!this.reset.nodeType)&&this.reset()})},e.fn.enable=function(e){return void 0===e&&(e=!0),this.each(function(){this.disabled=!e})},e.fn.selected=function(t){return void 0===t&&(t=!0),this.each(function(){var r=this.type;if("checkbox"==r||"radio"==r)this.checked=t;else if("option"==this.tagName.toLowerCase()){var a=e(this).parent("select");t&&a[0]&&"select-one"==a[0].type&&a.find("option").selected(!1),this.selected=t}})},e.fn.ajaxSubmit.debug=!1});
;
/*!
* jQuery UI Position 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){return function(){function h(e,t,n){return[parseFloat(e[0])*(l.test(e[0])?t/100:1),parseFloat(e[1])*(l.test(e[1])?n/100:1)]}function p(t,n){return parseInt(e.css(t,n),10)||0}function d(t){var n=t[0];return n.nodeType===9?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var t,n,r=Math.max,i=Math.abs,s=Math.round,o=/left|center|right/,u=/top|center|bottom/,a=/[\+\-]\d+(\.[\d]+)?%?/,f=/^\w+/,l=/%$/,c=e.fn.position;e.position={scrollbarWidth:function(){if(t!==undefined)return t;var n,r,i=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),s=i.children()[0];return e("body").append(i),n=s.offsetWidth,i.css("overflow","scroll"),r=s.offsetWidth,n===r&&(r=i[0].clientWidth),i.remove(),t=n-r},getScrollInfo:function(t){var n=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),r=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&&t.width<t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&&t.height<t.element[0].scrollHeight;return{width:s?e.position.scrollbarWidth():0,height:i?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]),i=!!n[0]&&n[0].nodeType===9;return{element:n,isWindow:r,isDocument:i,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r||i?n.width():n.outerWidth(),height:r||i?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return c.apply(this,arguments);t=e.extend({},t);var l,v,m,g,y,b,w=e(t.of),E=e.position.getWithinInfo(t.within),S=e.position.getScrollInfo(E),x=(t.collision||"flip").split(" "),T={};return b=d(w),w[0].preventDefault&&(t.at="left top"),v=b.width,m=b.height,g=b.offset,y=e.extend({},g),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=o.test(e[0])?e.concat(["center"]):u.test(e[0])?["center"].concat(e):["center","center"]),e[0]=o.test(e[0])?e[0]:"center",e[1]=u.test(e[1])?e[1]:"center",n=a.exec(e[0]),r=a.exec(e[1]),T[this]=[n?n[0]:0,r?r[0]:0],t[this]=[f.exec(e[0])[0],f.exec(e[1])[0]]}),x.length===1&&(x[1]=x[0]),t.at[0]==="right"?y.left+=v:t.at[0]==="center"&&(y.left+=v/2),t.at[1]==="bottom"?y.top+=m:t.at[1]==="center"&&(y.top+=m/2),l=h(T.at,v,m),y.left+=l[0],y.top+=l[1],this.each(function(){var o,u,a=e(this),f=a.outerWidth(),c=a.outerHeight(),d=p(this,"marginLeft"),b=p(this,"marginTop"),N=f+d+p(this,"marginRight")+S.width,C=c+b+p(this,"marginBottom")+S.height,k=e.extend({},y),L=h(T.my,a.outerWidth(),a.outerHeight());t.my[0]==="right"?k.left-=f:t.my[0]==="center"&&(k.left-=f/2),t.my[1]==="bottom"?k.top-=c:t.my[1]==="center"&&(k.top-=c/2),k.left+=L[0],k.top+=L[1],n||(k.left=s(k.left),k.top=s(k.top)),o={marginLeft:d,marginTop:b},e.each(["left","top"],function(n,r){e.ui.position[x[n]]&&e.ui.position[x[n]][r](k,{targetWidth:v,targetHeight:m,elemWidth:f,elemHeight:c,collisionPosition:o,collisionWidth:N,collisionHeight:C,offset:[l[0]+L[0],l[1]+L[1]],my:t.my,at:t.at,within:E,elem:a})}),t.using&&(u=function(e){var n=g.left-k.left,s=n+v-f,o=g.top-k.top,u=o+m-c,l={target:{element:w,left:g.left,top:g.top,width:v,height:m},element:{element:a,left:k.left,top:k.top,width:f,height:c},horizontal:s<0?"left":n>0?"right":"center",vertical:u<0?"top":o>0?"bottom":"middle"};v<f&&i(n+s)<v&&(l.horizontal="center"),m<c&&i(o+u)<m&&(l.vertical="middle"),r(i(n),i(s))>r(i(o),i(u))?l.important="horizontal":l.important="vertical",t.using.call(this,e,l)}),a.offset(e.extend(k,{using:u}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,i=n.isWindow?n.scrollLeft:n.offset.left,s=n.width,o=e.left-t.collisionPosition.marginLeft,u=i-o,a=o+t.collisionWidth-s-i,f;t.collisionWidth>s?u>0&&a<=0?(f=e.left+u+t.collisionWidth-s-i,e.left+=u-f):a>0&&u<=0?e.left=i:u>a?e.left=i+s-t.collisionWidth:e.left=i:u>0?e.left+=u:a>0?e.left-=a:e.left=r(e.left-o,e.left)},top:function(e,t){var n=t.within,i=n.isWindow?n.scrollTop:n.offset.top,s=t.within.height,o=e.top-t.collisionPosition.marginTop,u=i-o,a=o+t.collisionHeight-s-i,f;t.collisionHeight>s?u>0&&a<=0?(f=e.top+u+t.collisionHeight-s-i,e.top+=u-f):a>0&&u<=0?e.top=i:u>a?e.top=i+s-t.collisionHeight:e.top=i:u>0?e.top+=u:a>0?e.top-=a:e.top=r(e.top-o,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,s=n.width,o=n.isWindow?n.scrollLeft:n.offset.left,u=e.left-t.collisionPosition.marginLeft,a=u-o,f=u+t.collisionWidth-s-o,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a<0){p=e.left+l+c+h+t.collisionWidth-s-r;if(p<0||p<i(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-o;if(d>0||i(d)<f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,s=n.height,o=n.isWindow?n.scrollTop:n.offset.top,u=e.top-t.collisionPosition.marginTop,a=u-o,f=u+t.collisionHeight-s-o,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;if(a<0){v=e.top+c+h+p+t.collisionHeight-s-r;if(v<0||v<i(a))e.top+=c+h+p}else if(f>0){d=e.top-t.collisionPosition.marginTop+c+h+p-o;if(d>0||i(d)<f)e.top+=c+h+p}}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,r,i,s,o,u=document.getElementsByTagName("body")[0],a=document.createElement("div");t=document.createElement(u?"div":"body"),i={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},u&&e.extend(i,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in i)t.style[o]=i[o];t.appendChild(a),r=u||document.documentElement,r.insertBefore(t,r.firstChild),a.style.cssText="position: absolute; left: 10.7432222px;",s=e(a).offset().left,n=s>10&&s<11,t.innerHTML="",r.removeChild(t)}()}(),e.ui.position});;
/**
* @file
* Adapted from underscore.js with the addition Drupal namespace.
*/
/**
* Limits the invocations of a function in a given time frame.
*
* The debounce function wrapper should be used sparingly. One clear use case
* is limiting the invocation of a callback attached to the window resize event.
*
* Before using the debounce function wrapper, consider first whether the
* callback could be attached to an event that fires less frequently or if the
* function can be written in such a way that it is only invoked under specific
* conditions.
*
* @param {function} func
* The function to be invoked.
* @param {number} wait
* The time period within which the callback function should only be
* invoked once. For example if the wait period is 250ms, then the callback
* will only be called at most 4 times per second.
* @param {bool} immediate
* Whether we wait at the beginning or end to execute the function.
*
* @return {function}
* The debounced function.
*/
Drupal.debounce = function (func, wait, immediate) {
'use strict';
var timeout;
var result;
return function () {
var context = this;
var args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
};
;
/**
* @file
* Manages elements that can offset the size of the viewport.
*
* Measures and reports viewport offset dimensions from elements like the
* toolbar that can potentially displace the positioning of other elements.
*/
/**
* @typedef {object} Drupal~displaceOffset
*
* @prop {number} top
* @prop {number} left
* @prop {number} right
* @prop {number} bottom
*/
/**
* Triggers when layout of the page changes.
*
* This is used to position fixed element on the page during page resize and
* Toolbar toggling.
*
* @event drupalViewportOffsetChange
*/
(function ($, Drupal, debounce) {
'use strict';
/**
* @name Drupal.displace.offsets
*
* @type {Drupal~displaceOffset}
*/
var offsets = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
/**
* Registers a resize handler on the window.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.drupalDisplace = {
attach: function () {
// Mark this behavior as processed on the first pass.
if (this.displaceProcessed) {
return;
}
this.displaceProcessed = true;
$(window).on('resize.drupalDisplace', debounce(displace, 200));
}
};
/**
* Informs listeners of the current offset dimensions.
*
* @function Drupal.displace
*
* @prop {Drupal~displaceOffset} offsets
*
* @param {bool} [broadcast]
* When true or undefined, causes the recalculated offsets values to be
* broadcast to listeners.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*
* @fires event:drupalViewportOffsetChange
*/
function displace(broadcast) {
offsets = Drupal.displace.offsets = calculateOffsets();
if (typeof broadcast === 'undefined' || broadcast) {
$(document).trigger('drupalViewportOffsetChange', offsets);
}
return offsets;
}
/**
* Determines the viewport offsets.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*/
function calculateOffsets() {
return {
top: calculateOffset('top'),
right: calculateOffset('right'),
bottom: calculateOffset('bottom'),
left: calculateOffset('left')
};
}
/**
* Gets a specific edge's offset.
*
* Any element with the attribute data-offset-{edge} e.g. data-offset-top will
* be considered in the viewport offset calculations. If the attribute has a
* numeric value, that value will be used. If no value is provided, one will
* be calculated using the element's dimensions and placement.
*
* @function Drupal.displace.calculateOffset
*
* @param {string} edge
* The name of the edge to calculate. Can be 'top', 'right',
* 'bottom' or 'left'.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function calculateOffset(edge) {
var edgeOffset = 0;
var displacingElements = document.querySelectorAll('[data-offset-' + edge + ']');
var n = displacingElements.length;
for (var i = 0; i < n; i++) {
var el = displacingElements[i];
// If the element is not visible, do consider its dimensions.
if (el.style.display === 'none') {
continue;
}
// If the offset data attribute contains a displacing value, use it.
var displacement = parseInt(el.getAttribute('data-offset-' + edge), 10);
// If the element's offset data attribute exits
// but is not a valid number then get the displacement
// dimensions directly from the element.
if (isNaN(displacement)) {
displacement = getRawOffset(el, edge);
}
// If the displacement value is larger than the current value for this
// edge, use the displacement value.
edgeOffset = Math.max(edgeOffset, displacement);
}
return edgeOffset;
}
/**
* Calculates displacement for element based on its dimensions and placement.
*
* @param {HTMLElement} el
* The jQuery element whose dimensions and placement will be measured.
*
* @param {string} edge
* The name of the edge of the viewport that the element is associated
* with.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function getRawOffset(el, edge) {
var $el = $(el);
var documentElement = document.documentElement;
var displacement = 0;
var horizontal = (edge === 'left' || edge === 'right');
// Get the offset of the element itself.
var placement = $el.offset()[horizontal ? 'left' : 'top'];
// Subtract scroll distance from placement to get the distance
// to the edge of the viewport.
placement -= window['scroll' + (horizontal ? 'X' : 'Y')] || document.documentElement['scroll' + (horizontal ? 'Left' : 'Top')] || 0;
// Find the displacement value according to the edge.
switch (edge) {
// Left and top elements displace as a sum of their own offset value
// plus their size.
case 'top':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerHeight();
break;
case 'left':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerWidth();
break;
// Right and bottom elements displace according to their left and
// top offset. Their size isn't important.
case 'bottom':
displacement = documentElement.clientHeight - placement;
break;
case 'right':
displacement = documentElement.clientWidth - placement;
break;
default:
displacement = 0;
}
return displacement;
}
/**
* Assign the displace function to a property of the Drupal global object.
*
* @ignore
*/
Drupal.displace = displace;
$.extend(Drupal.displace, {
/**
* Expose offsets to other scripts to avoid having to recalculate offsets.
*
* @ignore
*/
offsets: offsets,
/**
* Expose method to compute a single edge offsets.
*
* @ignore
*/
calculateOffset: calculateOffset
});
})(jQuery, Drupal, Drupal.debounce);
;
/*! jquery.cookie v1.4.1 | MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});;
/**
* @file
* Drupal Bootstrap object.
*/
/**
* All Drupal Bootstrap JavaScript APIs are contained in this namespace.
*
* @namespace
*/
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.bootstrap = {
settings: drupalSettings.bootstrap || {}
};
/**
* Wraps Drupal.checkPlain() to ensure value passed isn't empty.
*
* Encodes special characters in a plain-text string for display as HTML.
*
* @param {string} str
* The string to be encoded.
*
* @return {string}
* The encoded string.
*
* @ingroup sanitization
*/
Drupal.bootstrap.checkPlain = function (str) {
return str && Drupal.checkPlain(str) || '';
};
/**
* Extends a Bootstrap plugin constructor.
*
* @param {string} id
* A Bootstrap plugin identifier located in $.fn.
* @param {function} [callback]
* A callback to extend the plugin constructor.
*
* @return {function|boolean}
* The Bootstrap plugin or FALSE if the plugin does not exist.
*/
Drupal.bootstrap.extendPlugin = function (id, callback) {
// Immediately return if the plugin does not exist.
if (!$.fn[id] || !$.fn[id].Constructor) return false;
// Extend the plugin if a callback was provided.
if ($.isFunction(callback)) {
var ret = callback.apply($.fn[id].Constructor, [this.settings]);
if ($.isPlainObject(ret)) {
$.extend(true, $.fn[id].Constructor, ret);
}
}
// Add a jQuery UI like option getter/setter method.
if ($.fn[id].Constructor.prototype.option === void(0)) {
$.fn[id].Constructor.prototype.option = this.option;
}
return $.fn[id].Constructor;
};
/**
* Replaces a Bootstrap jQuery plugin definition.
*
* @param {string} id
* A Bootstrap plugin identifier located in $.fn.
* @param {function} [callback]
* A callback to replace the jQuery plugin definition. The callback must
* return a function that is used to construct a jQuery plugin.
*
* @return {function|boolean}
* The Bootstrap jQuery plugin definition or FALSE if the plugin does not
* exist.
*/
Drupal.bootstrap.replacePlugin = function (id, callback) {
// Immediately return if plugin does not exist or not a valid callback.
if (!$.fn[id] || !$.fn[id].Constructor || !$.isFunction(callback)) return false;
var constructor = $.fn[id].Constructor;
var plugin = callback.apply(constructor);
if ($.isFunction(plugin)) {
plugin.Constructor = constructor;
var old = $.fn[id];
plugin.noConflict = function () {
$.fn[id] = old;
return this;
};
$.fn[id] = plugin;
}
};
/**
* Map of supported events by regular expression.
*
* @type {Object<Event|MouseEvent|KeyboardEvent|TouchEvent,RegExp>}
*/
Drupal.bootstrap.eventMap = {
Event: /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
MouseEvent: /^(?:click|dblclick|mouse(?:down|enter|leave|up|over|move|out))$/,
KeyboardEvent: /^(?:key(?:down|press|up))$/,
TouchEvent: /^(?:touch(?:start|end|move|cancel))$/
};
/**
* Simulates a native event on an element in the browser.
*
* Note: This is a pretty complete modern implementation. If things are quite
* working the way you intend (in older browsers), you may wish to use the
* jQuery.simulate plugin. If it's available, this method will defer to it.
*
* @see https://github.com/jquery/jquery-simulate
*
* @param {HTMLElement} element
* A DOM element to dispatch event on.
* @param {String} type
* The type of event to simulate.
* @param {Object} [options]
* An object of options to pass to the event constructor. Typically, if
* an event is being proxied, you should just pass the original event
* object here. This allows, if the browser supports it, to be a truly
* simulated event.
*/
Drupal.bootstrap.simulate = function (element, type, options) {
// Defer to the jQuery.simulate plugin, if it's available.
if (typeof $.simulate === 'function') {
new $.simulate(element, type, options);
return;
}
var event;
var ctor;
for (var name in Drupal.bootstrap.eventMap) {
if (Drupal.bootstrap.eventMap[name].test(type)) {
ctor = name;
break;
}
}
if (!ctor) {
throw new SyntaxError('Only rudimentary HTMLEvents, KeyboardEvents and MouseEvents are supported: ' + type);
}
var opts = {bubbles: true, cancelable: true};
if (ctor === 'KeyboardEvent' || ctor === 'MouseEvent') {
$.extend(opts, {ctrlKey: !1, altKey: !1, shiftKey: !1, metaKey: !1});
}
if (ctor === 'MouseEvent') {
$.extend(opts, {button: 0, pointerX: 0, pointerY: 0, view: window});
}
if (options) {
$.extend(opts, options);
}
if (typeof window[ctor] === 'function') {
event = new window[ctor](type, opts);
element.dispatchEvent(event);
}
else if (document.createEvent) {
event = document.createEvent(ctor);
event.initEvent(type, opts.bubbles, opts.cancelable);
element.dispatchEvent(event);
}
else if (typeof element.fireEvent === 'function') {
event = $.extend(document.createEventObject(), opts);
element.fireEvent('on' + type, event);
}
else if (typeof element[type]) {
element[type]();
}
};
/**
* Provide jQuery UI like ability to get/set options for Bootstrap plugins.
*
* @param {string|object} key
* A string value of the option to set, can be dot like to a nested key.
* An object of key/value pairs.
* @param {*} [value]
* (optional) A value to set for key.
*
* @returns {*}
* - Returns nothing if key is an object or both key and value parameters
* were provided to set an option.
* - Returns the a value for a specific setting if key was provided.
* - Returns an object of key/value pairs of all the options if no key or
* value parameter was provided.
*
* @see https://github.com/jquery/jquery-ui/blob/master/ui/widget.js
*
* @todo This isn't fully working since Bootstrap plugins don't allow
* methods to return values.
*/
Drupal.bootstrap.option = function (key, value) {
var options = key;
var parts, curOption, i;
// Don't return a reference to the internal hash.
if (arguments.length === 0) {
return $.extend({}, this.options);
}
// Handle a specific option.
if (typeof key === "string") {
// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split(".");
key = parts.shift();
if (parts.length) {
curOption = options[key] = $.extend({}, this.options[key]);
for (i = 0; i < parts.length - 1; i++) {
curOption[parts[i]] = curOption[parts[i]] || {};
curOption = curOption[parts[i]];
}
key = parts.pop();
if (arguments.length === 1) {
return curOption[key] === undefined ? null : curOption[key];
}
curOption[key] = value;
}
else {
if (arguments.length === 1) {
return this.options[key] === undefined ? null : this.options[key];
}
options[key] = value;
}
}
// Set the new option(s).
for (key in options) {
if (!options.hasOwnProperty(key)) continue;
this.options[key] = options[key];
}
return this;
};
})(window.jQuery, window.Drupal, window.drupalSettings);
;
(function ($, _) {
/**
* Class to help modify attributes.
*
* @param {object} object
* An object to initialize attributes with.
*
* @constructor
*/
var Attributes = function (object) {
this.data = object && _.isObject(object) && _.clone(object) || {};
};
/**
* Renders the attributes object as a string to inject into an HTML element.
*
* @returns {string}
*/
Attributes.prototype.toString = function () {
var output = '';
var name, value;
var checkPlain = function (str) {
return str && str.toString().replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>') || '';
};
for (name in this.data) {
if (!this.data.hasOwnProperty(name)) continue;
value = this.data[name];
if (_.isFunction(value)) value = value();
if (_.isObject(value)) value = _.values(value);
if (_.isArray(value)) value = value.join(' ');
output += ' ' + checkPlain(name) + '="' + checkPlain(value) + '"';
}
return output;
};
/**
* Add class(es) to the array.
*
* @param {string|Array} value
* An individual class or an array of classes to add.
*
* @return {Attributes}
*
* @chainable
*/
Attributes.prototype.addClass = function (value) {
var classes = this.getClasses();
value = [].concat(classes, value);
this.set('class', _.uniq(value));
return this;
};
/**
* Returns whether the requested attribute exists.
*
* @param {string} name
* An attribute name to check.
*
* @return {boolean}
* TRUE or FALSE
*/
Attributes.prototype.exists = function (name) {
return this.data[name] !== void(0) && this.data[name] !== null;
};
/**
* Retrieve a specific attribute from the array.
*
* @param {string} name
* The specific attribute to retrieve.
* @param {*} defaultValue
* (optional) The default value to set if the attribute does not exist.
*
* @return {*}
* A specific attribute value, passed by reference.
*/
Attributes.prototype.get = function (name, defaultValue) {
if (!this.exists(name)) this.data[name] = defaultValue;
return this.data[name];
};
/**
* Retrieves a cloned copy of the internal attributes data object.
*
* @returns {Object}
*/
Attributes.prototype.getData = function () {
return _.clone(this.data);
};
/**
* Retrieves classes from the array.
*
* @return {Array}
* The classes array.
*/
Attributes.prototype.getClasses = function () {
var classes = [].concat(this.get('class', []));
return _.uniq(classes);
};
/**
* Indicates whether a class is present in the array.
*
* @param {string|Array} name
* The class(es) to search for.
*
* @return {boolean}
* TRUE or FALSE
*/
Attributes.prototype.hasClass = function (name) {
name = [].concat(name);
var classes = this.getClasses();
var found = false;
_.each(name, function (value) { if (_.indexOf(classes, value) !== -1) found = true; });
return found;
};
/**
* Merges multiple values into the array.
*
* @param {object} values
* An associative key/value array.
* @param {boolean} [recursive]
* Flag determining whether or not to recursively merge key/value pairs.
*
* @return {Attributes}
*
* @chainable
*/
Attributes.prototype.merge = function (values, recursive) {
values = values instanceof Attributes ? values.getData() : values;
if (recursive === void(0) || recursive) {
this.data = $.extend(true, {}, this.data, values);
}
else {
$.extend(this.data, values);
}
return this;
};
/**
* Removes an attribute from the array.
*
* @param {string} name
* The name of the attribute to remove.
*
* @return {Attributes}
*
* @chainable
*/
Attributes.prototype.remove = function (name) {
if (this.exists(name)) delete this.data[name];
return this;
};
/**
* Removes a class from the attributes array.
*
* @param {string|Array} value
* An individual class or an array of classes to remove.
*
* @return {Attributes}
*
* @chainable
*/
Attributes.prototype.removeClass = function (value) {
this.set('class', _.without(this.getClasses(), [].concat(value)));
return this;
};
/**
* Replaces a class in the attributes array.
*
* @param {string} oldValue
* The old class to remove.
* @param {string} newValue
* The new class. It will not be added if the old class does not exist.
*
* @return {Attributes}
*
* @chainable
*/
Attributes.prototype.replaceClass = function (oldValue, newValue) {
var classes = this.getClasses();
var i = _.indexOf(oldValue, classes);
if (i >= 0) {
classes[i] = newValue;
this.set('class', classes);
}
return this;
};
/**
* Sets an attribute on the array.
*
* @param {string} name
* The name of the attribute to set.
* @param {*} value
* The value of the attribute to set.
*
* @return {Attributes}
*
* @chainable
*/
Attributes.prototype.set = function (name, value) {
this.data[name] = value;
return this;
};
/**
* Creates an Attributes instance.
*
* @param {object|Attributes} object
* An object to initialize attributes with.
*
* @returns {Attributes}
*
* @global
*
* @constructor
*/
window.Attributes = function (object) {
return object instanceof Attributes ? object : new Attributes(object);
};
})(window.jQuery, window._);
;
/**
* @file
* Theme hooks for the Drupal Bootstrap base theme.
*/
(function ($, Drupal, Bootstrap) {
/**
* Fallback for theming an icon if the Icon API module is not installed.
*/
if (!Drupal.icon) Drupal.icon = { bundles: {} };
if (!Drupal.theme.icon || Drupal.theme.prototype.icon) {
$.extend(Drupal.theme, /** @lends Drupal.theme */ {
/**
* Renders an icon.
*
* @param {string} bundle
* The bundle which the icon belongs to.
* @param {string} icon
* The name of the icon to render.
* @param {object|Attributes} [attributes]
* An object of attributes to also apply to the icon.
*
* @returns {string}
*/
icon: function (bundle, icon, attributes) {
if (!Drupal.icon.bundles[bundle]) return '';
attributes = Attributes(attributes).addClass('icon').set('aria-hidden', 'true');
icon = Drupal.icon.bundles[bundle](icon, attributes);
return '<span' + attributes + '></span>';
}
});
}
/**
* Callback for modifying an icon in the "bootstrap" icon bundle.
*
* @param {string} icon
* The icon being rendered.
* @param {Attributes} attributes
* Attributes object for the icon.
*/
Drupal.icon.bundles.bootstrap = function (icon, attributes) {
attributes.addClass(['glyphicon', 'glyphicon-' + icon]);
};
/**
* Add necessary theming hooks.
*/
$.extend(Drupal.theme, /** @lends Drupal.theme */ {
/**
* Renders a Bootstrap AJAX glyphicon throbber.
*
* @returns {string}
*/
ajaxThrobber: function () {
return Drupal.theme.bootstrapIcon('refresh', {'class': ['ajax-throbber', 'glyphicon-spin'] });
},
/**
* Renders a button element.
*
* @param {object|Attributes} attributes
* An object of attributes to apply to the button. If it contains one of:
* - value: The label of the button.
* - context: The context type of Bootstrap button, can be one of:
* - default
* - primary
* - success
* - info
* - warning
* - danger
* - link
*
* @returns {string}
*/
button: function (attributes) {
attributes = Attributes(attributes).addClass('btn');
var context = attributes.get('context', 'default');
var label = attributes.get('value', '');
attributes.remove('context').remove('value');
if (!attributes.hasClass(['btn-default', 'btn-primary', 'btn-success', 'btn-info', 'btn-warning', 'btn-danger', 'btn-link'])) {
attributes.addClass('btn-' + Bootstrap.checkPlain(context));
}
return '<button' + attributes + '>' + label + '</button>';
},
/**
* Alias for "button" theme hook.
*
* @param {object|Attributes} attributes
* An object of attributes to apply to the button.
*
* @see Drupal.theme.button()
*
* @returns {string}
*/
btn: function (attributes) {
return Drupal.theme('button', attributes);
},
/**
* Renders a button block element.
*
* @param {object|Attributes} attributes
* An object of attributes to apply to the button.
*
* @see Drupal.theme.button()
*
* @returns {string}
*/
'btn-block': function (attributes) {
return Drupal.theme('button', Attributes(attributes).addClass('btn-block'));
},
/**
* Renders a large button element.
*
* @param {object|Attributes} attributes
* An object of attributes to apply to the button.
*
* @see Drupal.theme.button()
*
* @returns {string}
*/
'btn-lg': function (attributes) {
return Drupal.theme('button', Attributes(attributes).addClass('btn-lg'));
},
/**
* Renders a small button element.
*
* @param {object|Attributes} attributes
* An object of attributes to apply to the button.
*
* @see Drupal.theme.button()
*
* @returns {string}
*/
'btn-sm': function (attributes) {
return Drupal.theme('button', Attributes(attributes).addClass('btn-sm'));
},
/**
* Renders an extra small button element.
*
* @param {object|Attributes} attributes
* An object of attributes to apply to the button.
*
* @see Drupal.theme.button()
*
* @returns {string}
*/
'btn-xs': function (attributes) {
return Drupal.theme('button', Attributes(attributes).addClass('btn-xs'));
},
/**
* Renders a glyphicon.
*
* @param {string} name
* The name of the glyphicon.
* @param {object|Attributes} [attributes]
* An object of attributes to apply to the icon.
*
* @returns {string}
*/
bootstrapIcon: function (name, attributes) {
return Drupal.theme('icon', 'bootstrap', name, attributes);
}
});
})(window.jQuery, window.Drupal, window.Drupal.bootstrap);
;
/**
* @file
* Form features.
*/
/**
* Triggers when a value in the form changed.
*
* The event triggers when content is typed or pasted in a text field, before
* the change event triggers.
*
* @event formUpdated
*/
(function ($, Drupal, debounce) {
'use strict';
/**
* Retrieves the summary for the first element.
*
* @return {string}
* The text of the summary.
*/
$.fn.drupalGetSummary = function () {
var callback = this.data('summaryCallback');
return (this[0] && callback) ? $.trim(callback(this[0])) : '';
};
/**
* Sets the summary for all matched elements.
*
* @param {function} callback
* Either a function that will be called each time the summary is
* retrieved or a string (which is returned each time).
*
* @return {jQuery}
* jQuery collection of the current element.
*
* @fires event:summaryUpdated
*
* @listens event:formUpdated
*/
$.fn.drupalSetSummary = function (callback) {
var self = this;
// To facilitate things, the callback should always be a function. If it's
// not, we wrap it into an anonymous function which just returns the value.
if (typeof callback !== 'function') {
var val = callback;
callback = function () { return val; };
}
return this
.data('summaryCallback', callback)
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.off('formUpdated.summary')
.on('formUpdated.summary', function () {
self.trigger('summaryUpdated');
})
// The actual summaryUpdated handler doesn't fire when the callback is
// changed, so we have to do this manually.
.trigger('summaryUpdated');
};
/**
* Prevents consecutive form submissions of identical form values.
*
* Repetitive form submissions that would submit the identical form values
* are prevented, unless the form values are different to the previously
* submitted values.
*
* This is a simplified re-implementation of a user-agent behavior that
* should be natively supported by major web browsers, but at this time, only
* Firefox has a built-in protection.
*
* A form value-based approach ensures that the constraint is triggered for
* consecutive, identical form submissions only. Compared to that, a form
* button-based approach would (1) rely on [visible] buttons to exist where
* technically not required and (2) require more complex state management if
* there are multiple buttons in a form.
*
* This implementation is based on form-level submit events only and relies
* on jQuery's serialize() method to determine submitted form values. As such,
* the following limitations exist:
*
* - Event handlers on form buttons that preventDefault() do not receive a
* double-submit protection. That is deemed to be fine, since such button
* events typically trigger reversible client-side or server-side
* operations that are local to the context of a form only.
* - Changed values in advanced form controls, such as file inputs, are not
* part of the form values being compared between consecutive form submits
* (due to limitations of jQuery.serialize()). That is deemed to be
* acceptable, because if the user forgot to attach a file, then the size of
* HTTP payload will most likely be small enough to be fully passed to the
* server endpoint within (milli)seconds. If a user mistakenly attached a
* wrong file and is technically versed enough to cancel the form submission
* (and HTTP payload) in order to attach a different file, then that
* edge-case is not supported here.
*
* Lastly, all forms submitted via HTTP GET are idempotent by definition of
* HTTP standards, so excluded in this implementation.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.formSingleSubmit = {
attach: function () {
function onFormSubmit(e) {
var $form = $(e.currentTarget);
var formValues = $form.serialize();
var previousValues = $form.attr('data-drupal-form-submit-last');
if (previousValues === formValues) {
e.preventDefault();
}
else {
$form.attr('data-drupal-form-submit-last', formValues);
}
}
$('body').once('form-single-submit')
.on('submit.singleSubmit', 'form:not([method~="GET"])', onFormSubmit);
}
};
/**
* Sends a 'formUpdated' event each time a form element is modified.
*
* @param {HTMLElement} element
* The element to trigger a form updated event on.
*
* @fires event:formUpdated
*/
function triggerFormUpdated(element) {
$(element).trigger('formUpdated');
}
/**
* Collects the IDs of all form fields in the given form.
*
* @param {HTMLFormElement} form
* The form element to search.
*
* @return {Array}
* Array of IDs for form fields.
*/
function fieldsList(form) {
var $fieldList = $(form).find('[name]').map(function (index, element) {
// We use id to avoid name duplicates on radio fields and filter out
// elements with a name but no id.
return element.getAttribute('id');
});
// Return a true array.
return $.makeArray($fieldList);
}
/**
* Triggers the 'formUpdated' event on form elements when they are modified.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches formUpdated behaviors.
* @prop {Drupal~behaviorDetach} detach
* Detaches formUpdated behaviors.
*
* @fires event:formUpdated
*/
Drupal.behaviors.formUpdated = {
attach: function (context) {
var $context = $(context);
var contextIsForm = $context.is('form');
var $forms = (contextIsForm ? $context : $context.find('form')).once('form-updated');
var formFields;
if ($forms.length) {
// Initialize form behaviors, use $.makeArray to be able to use native
// forEach array method and have the callback parameters in the right
// order.
$.makeArray($forms).forEach(function (form) {
var events = 'change.formUpdated input.formUpdated ';
var eventHandler = debounce(function (event) { triggerFormUpdated(event.target); }, 300);
formFields = fieldsList(form).join(',');
form.setAttribute('data-drupal-form-fields', formFields);
$(form).on(events, eventHandler);
});
}
// On ajax requests context is the form element.
if (contextIsForm) {
formFields = fieldsList(context).join(',');
// @todo replace with form.getAttribute() when #1979468 is in.
var currentFields = $(context).attr('data-drupal-form-fields');
// If there has been a change in the fields or their order, trigger
// formUpdated.
if (formFields !== currentFields) {
triggerFormUpdated(context);
}
}
},
detach: function (context, settings, trigger) {
var $context = $(context);
var contextIsForm = $context.is('form');
if (trigger === 'unload') {
var $forms = (contextIsForm ? $context : $context.find('form')).removeOnce('form-updated');
if ($forms.length) {
$.makeArray($forms).forEach(function (form) {
form.removeAttribute('data-drupal-form-fields');
$(form).off('.formUpdated');
});
}
}
}
};
/**
* Prepopulate form fields with information from the visitor browser.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the behavior for filling user info from browser.
*/
Drupal.behaviors.fillUserInfoFromBrowser = {
attach: function (context, settings) {
var userInfo = ['name', 'mail', 'homepage'];
var $forms = $('[data-user-info-from-browser]').once('user-info-from-browser');
if ($forms.length) {
userInfo.map(function (info) {
var $element = $forms.find('[name=' + info + ']');
var browserData = localStorage.getItem('Drupal.visitor.' + info);
var emptyOrDefault = ($element.val() === '' || ($element.attr('data-drupal-default-value') === $element.val()));
if ($element.length && emptyOrDefault && browserData) {
$element.val(browserData);
}
});
}
$forms.on('submit', function () {
userInfo.map(function (info) {
var $element = $forms.find('[name=' + info + ']');
if ($element.length) {
localStorage.setItem('Drupal.visitor.' + info, $element.val());
}
});
});
}
};
})(jQuery, Drupal, Drupal.debounce);
;
/**
* @file
* Extends methods from core/misc/form.js.
*/
(function ($, window, Drupal, drupalSettings) {
/**
* Behavior for "forms_has_error_value_toggle" theme setting.
*/
Drupal.behaviors.bootstrapForm = {
attach: function (context) {
if (drupalSettings.bootstrap && drupalSettings.bootstrap.forms_has_error_value_toggle) {
var $context = $(context);
$context.find('.form-item.has-error:not(.form-type-password.has-feedback)').once('error').each(function () {
var $formItem = $(this);
var $input = $formItem.find(':input');
$input.on('keyup focus blur', function () {
if (this.defaultValue !== void 0) {
$formItem[this.defaultValue !== this.value ? 'addClass' : 'addClass']('has-error');
$input[this.defaultValue !== this.value ? 'addClass' : 'removeClass']('error');
}
});
});
}
}
};
})(jQuery, this, Drupal, drupalSettings);
;
/**
* @file
* Progress bar.
*/
(function ($, Drupal) {
'use strict';
/**
* Theme function for the progress bar.
*
* @param {string} id
* The id for the progress bar.
*
* @return {string}
* The HTML for the progress bar.
*/
Drupal.theme.progressBar = function (id) {
return '<div id="' + id + '" class="progress" aria-live="polite">' +
'<div class="progress__label"> </div>' +
'<div class="progress__track"><div class="progress__bar"></div></div>' +
'<div class="progress__percentage"></div>' +
'<div class="progress__description"> </div>' +
'</div>';
};
/**
* A progressbar object. Initialized with the given id. Must be inserted into
* the DOM afterwards through progressBar.element.
*
* Method is the function which will perform the HTTP request to get the
* progress bar state. Either "GET" or "POST".
*
* @example
* pb = new Drupal.ProgressBar('myProgressBar');
* some_element.appendChild(pb.element);
*
* @constructor
*
* @param {string} id
* The id for the progressbar.
* @param {function} updateCallback
* Callback to run on update.
* @param {string} method
* HTTP method to use.
* @param {function} errorCallback
* Callback to call on error.
*/
Drupal.ProgressBar = function (id, updateCallback, method, errorCallback) {
this.id = id;
this.method = method || 'GET';
this.updateCallback = updateCallback;
this.errorCallback = errorCallback;
// The WAI-ARIA setting aria-live="polite" will announce changes after
// users
// have completed their current activity and not interrupt the screen
// reader.
this.element = $(Drupal.theme('progressBar', id));
};
$.extend(Drupal.ProgressBar.prototype, /** @lends Drupal.ProgressBar# */{
/**
* Set the percentage and status message for the progressbar.
*
* @param {number} percentage
* The progress percentage.
* @param {string} message
* The message to show the user.
* @param {string} label
* The text for the progressbar label.
*/
setProgress: function (percentage, message, label) {
if (percentage >= 0 && percentage <= 100) {
$(this.element).find('div.progress__bar').css('width', percentage + '%');
$(this.element).find('div.progress__percentage').html(percentage + '%');
}
$('div.progress__description', this.element).html(message);
$('div.progress__label', this.element).html(label);
if (this.updateCallback) {
this.updateCallback(percentage, message, this);
}
},
/**
* Start monitoring progress via Ajax.
*
* @param {string} uri
* The URI to use for monitoring.
* @param {number} delay
* The delay for calling the monitoring URI.
*/
startMonitoring: function (uri, delay) {
this.delay = delay;
this.uri = uri;
this.sendPing();
},
/**
* Stop monitoring progress via Ajax.
*/
stopMonitoring: function () {
clearTimeout(this.timer);
// This allows monitoring to be stopped from within the callback.
this.uri = null;
},
/**
* Request progress data from server.
*/
sendPing: function () {
if (this.timer) {
clearTimeout(this.timer);
}
if (this.uri) {
var pb = this;
// When doing a post request, you need non-null data. Otherwise a
// HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
var uri = this.uri;
if (uri.indexOf('?') === -1) {
uri += '?';
}
else {
uri += '&';
}
uri += '_format=json';
$.ajax({
type: this.method,
url: uri,
data: '',
dataType: 'json',
success: function (progress) {
// Display errors.
if (progress.status === 0) {
pb.displayError(progress.data);
return;
}
// Update display.
pb.setProgress(progress.percentage, progress.message, progress.label);
// Schedule next timer.
pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay);
},
error: function (xmlhttp) {
var e = new Drupal.AjaxError(xmlhttp, pb.uri);
pb.displayError('<pre>' + e.message + '</pre>');
}
});
}
},
/**
* Display errors on the page.
*
* @param {string} string
* The error message to show the user.
*/
displayError: function (string) {
var error = $('<div class="messages messages--error"></div>').html(string);
$(this.element).before(error).hide();
if (this.errorCallback) {
this.errorCallback(this);
}
}
});
})(jQuery, Drupal);
;
/**
* @file
* Extends methods from core/misc/progress.js.
*/
(function ($, Drupal) {
'use strict';
/**
* Theme function for the progress bar.
*
* @param {string} id
*
* @return {string}
* The HTML for the progress bar.
*/
Drupal.theme.progressBar = function (id) {
return '<div class="progress-wrapper" aria-live="polite">' +
'<div class="message"></div>'+
'<div id ="' + id + '" class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">' +
'<span class="percentage"></span>' +
'</div>' +
'</div>' +
'<div class="progress-label"></div>' +
'</div>';
};
$.extend(Drupal.ProgressBar.prototype, /** @lends Drupal.ProgressBar */{
/**
* Set the percentage and status message for the progressbar.
*
* @param {number} percentage
* @param {string} message
* @param {string} label
*/
setProgress: function (percentage, message, label) {
if (percentage >= 0 && percentage <= 100) {
$(this.element).find('.progress-bar').css('width', percentage + '%').attr('aria-valuenow', percentage);
$(this.element).find('.percentage').html(percentage + '%');
}
if (message) {
// Remove the unnecessary whitespace at the end of the message.
message = message.replace(/<br\/> |\s*$/, '');
$('.message', this.element).html(message);
}
if (label) {
$('.progress-label', this.element).html(label);
}
if (this.updateCallback) {
this.updateCallback(percentage, message, this);
}
},
/**
* Display errors on the page.
*
* @param {string} string
*/
displayError: function (string) {
var error = $('<div class="alert alert-block alert-error"><a class="close" data-dismiss="alert" href="#">×</a><h4>' + Drupal.t('Error message') + '</h4></div>').append(string);
$(this.element).before(error).hide();
if (this.errorCallback) {
this.errorCallback(this);
}
}
});
})(jQuery, Drupal);
;
/**
* @file
* Provides Ajax page updating via jQuery $.ajax.
*
* Ajax is a method of making a request via JavaScript while viewing an HTML
* page. The request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*/
(function ($, window, Drupal, drupalSettings) {
'use strict';
/**
* Attaches the Ajax behavior to each Ajax form element.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Initialize all {@link Drupal.Ajax} objects declared in
* `drupalSettings.ajax` or initialize {@link Drupal.Ajax} objects from
* DOM elements having the `use-ajax-submit` or `use-ajax` css class.
* @prop {Drupal~behaviorDetach} detach
* During `unload` remove all {@link Drupal.Ajax} objects related to
* the removed content.
*/
Drupal.behaviors.AJAX = {
attach: function (context, settings) {
function loadAjaxBehavior(base) {
var element_settings = settings.ajax[base];
if (typeof element_settings.selector === 'undefined') {
element_settings.selector = '#' + base;
}
$(element_settings.selector).once('drupal-ajax').each(function () {
element_settings.element = this;
element_settings.base = base;
Drupal.ajax(element_settings);
});
}
// Load all Ajax behaviors specified in the settings.
for (var base in settings.ajax) {
if (settings.ajax.hasOwnProperty(base)) {
loadAjaxBehavior(base);
}
}
// Bind Ajax behaviors to all items showing the class.
$('.use-ajax').once('ajax').each(function () {
var element_settings = {};
// Clicked links look better with the throbber than the progress bar.
element_settings.progress = {type: 'throbber'};
// For anchor tags, these will go to the target of the anchor rather
// than the usual location.
var href = $(this).attr('href');
if (href) {
element_settings.url = href;
element_settings.event = 'click';
}
element_settings.dialogType = $(this).data('dialog-type');
element_settings.dialog = $(this).data('dialog-options');
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
// This class means to submit the form to the action using Ajax.
$('.use-ajax-submit').once('ajax').each(function () {
var element_settings = {};
// Ajax submits specified in this manner automatically submit to the
// normal form action.
element_settings.url = $(this.form).attr('action');
// Form submit button clicks need to tell the form what was clicked so
// it gets passed in the POST request.
element_settings.setClick = true;
// Form buttons use the 'click' event rather than mousedown.
element_settings.event = 'click';
// Clicked form buttons look better with the throbber than the progress
// bar.
element_settings.progress = {type: 'throbber'};
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
Drupal.ajax.expired().forEach(function (instance) {
// Set this to null and allow garbage collection to reclaim
// the memory.
Drupal.ajax.instances[instance.instanceIndex] = null;
});
}
}
};
/**
* Extends Error to provide handling for Errors in Ajax.
*
* @constructor
*
* @augments Error
*
* @param {XMLHttpRequest} xmlhttp
* XMLHttpRequest object used for the failed request.
* @param {string} uri
* The URI where the error occurred.
* @param {string} customMessage
* The custom message.
*/
Drupal.AjaxError = function (xmlhttp, uri, customMessage) {
var statusCode;
var statusText;
var pathText;
var responseText;
var readyStateText;
if (xmlhttp.status) {
statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', {'!status': xmlhttp.status});
}
else {
statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.');
}
statusCode += '\n' + Drupal.t('Debugging information follows.');
pathText = '\n' + Drupal.t('Path: !uri', {'!uri': uri});
statusText = '';
// In some cases, when statusCode === 0, xmlhttp.statusText may not be
// defined. Unfortunately, testing for it with typeof, etc, doesn't seem to
// catch that and the test causes an exception. So we need to catch the
// exception here.
try {
statusText = '\n' + Drupal.t('StatusText: !statusText', {'!statusText': $.trim(xmlhttp.statusText)});
}
catch (e) {
// Empty.
}
responseText = '';
// Again, we don't have a way to know for sure whether accessing
// xmlhttp.responseText is going to throw an exception. So we'll catch it.
try {
responseText = '\n' + Drupal.t('ResponseText: !responseText', {'!responseText': $.trim(xmlhttp.responseText)});
}
catch (e) {
// Empty.
}
// Make the responseText more readable by stripping HTML tags and newlines.
responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
responseText = responseText.replace(/[\n]+\s+/g, '\n');
// We don't need readyState except for status == 0.
readyStateText = xmlhttp.status === 0 ? ('\n' + Drupal.t('ReadyState: !readyState', {'!readyState': xmlhttp.readyState})) : '';
customMessage = customMessage ? ('\n' + Drupal.t('CustomMessage: !customMessage', {'!customMessage': customMessage})) : '';
/**
* Formatted and translated error message.
*
* @type {string}
*/
this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
/**
* Used by some browsers to display a more accurate stack trace.
*
* @type {string}
*/
this.name = 'AjaxError';
};
Drupal.AjaxError.prototype = new Error();
Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
/**
* Provides Ajax page updating via jQuery $.ajax.
*
* This function is designed to improve developer experience by wrapping the
* initialization of {@link Drupal.Ajax} objects and storing all created
* objects in the {@link Drupal.ajax.instances} array.
*
* @example
* Drupal.behaviors.myCustomAJAXStuff = {
* attach: function (context, settings) {
*
* var ajaxSettings = {
* url: 'my/url/path',
* // If the old version of Drupal.ajax() needs to be used those
* // properties can be added
* base: 'myBase',
* element: $(context).find('.someElement')
* };
*
* var myAjaxObject = Drupal.ajax(ajaxSettings);
*
* // Declare a new Ajax command specifically for this Ajax object.
* myAjaxObject.commands.insert = function (ajax, response, status) {
* $('#my-wrapper').append(response.data);
* alert('New content was appended to #my-wrapper');
* };
*
* // This command will remove this Ajax object from the page.
* myAjaxObject.commands.destroyObject = function (ajax, response, status) {
* Drupal.ajax.instances[this.instanceIndex] = null;
* };
*
* // Programmatically trigger the Ajax request.
* myAjaxObject.execute();
* }
* };
*
* @param {object} settings
* The settings object passed to {@link Drupal.Ajax} constructor.
* @param {string} [settings.base]
* Base is passed to {@link Drupal.Ajax} constructor as the 'base'
* parameter.
* @param {HTMLElement} [settings.element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
*
* @return {Drupal.Ajax}
* The created Ajax object.
*
* @see Drupal.AjaxCommands
*/
Drupal.ajax = function (settings) {
if (arguments.length !== 1) {
throw new Error('Drupal.ajax() function must be called with one configuration object only');
}
// Map those config keys to variables for the old Drupal.ajax function.
var base = settings.base || false;
var element = settings.element || false;
delete settings.base;
delete settings.element;
// By default do not display progress for ajax calls without an element.
if (!settings.progress && !element) {
settings.progress = false;
}
var ajax = new Drupal.Ajax(base, element, settings);
ajax.instanceIndex = Drupal.ajax.instances.length;
Drupal.ajax.instances.push(ajax);
return ajax;
};
/**
* Contains all created Ajax objects.
*
* @type {Array.<Drupal.Ajax|null>}
*/
Drupal.ajax.instances = [];
/**
* List all objects where the associated element is not in the DOM
*
* This method ignores {@link Drupal.Ajax} objects not bound to DOM elements
* when created with {@link Drupal.ajax}.
*
* @return {Array.<Drupal.Ajax>}
* The list of expired {@link Drupal.Ajax} objects.
*/
Drupal.ajax.expired = function () {
return Drupal.ajax.instances.filter(function (instance) {
return instance && instance.element !== false && !document.body.contains(instance.element);
});
};
/**
* Settings for an Ajax object.
*
* @typedef {object} Drupal.Ajax~element_settings
*
* @prop {string} url
* Target of the Ajax request.
* @prop {?string} [event]
* Event bound to settings.element which will trigger the Ajax request.
* @prop {bool} [keypress=true]
* Triggers a request on keypress events.
* @prop {?string} selector
* jQuery selector targeting the element to bind events to or used with
* {@link Drupal.AjaxCommands}.
* @prop {string} [effect='none']
* Name of the jQuery method to use for displaying new Ajax content.
* @prop {string|number} [speed='none']
* Speed with which to apply the effect.
* @prop {string} [method]
* Name of the jQuery method used to insert new content in the targeted
* element.
* @prop {object} [progress]
* Settings for the display of a user-friendly loader.
* @prop {string} [progress.type='throbber']
* Type of progress element, core provides `'bar'`, `'throbber'` and
* `'fullscreen'`.
* @prop {string} [progress.message=Drupal.t('Please wait...')]
* Custom message to be used with the bar indicator.
* @prop {object} [submit]
* Extra data to be sent with the Ajax request.
* @prop {bool} [submit.js=true]
* Allows the PHP side to know this comes from an Ajax request.
* @prop {object} [dialog]
* Options for {@link Drupal.dialog}.
* @prop {string} [dialogType]
* One of `'modal'` or `'dialog'`.
* @prop {string} [prevent]
* List of events on which to stop default action and stop propagation.
*/
/**
* Ajax constructor.
*
* The Ajax request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*
* @constructor
*
* @param {string} [base]
* Base parameter of {@link Drupal.Ajax} constructor
* @param {HTMLElement} [element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
* @param {Drupal.Ajax~element_settings} element_settings
* Settings for this Ajax object.
*/
Drupal.Ajax = function (base, element, element_settings) {
var defaults = {
event: element ? 'mousedown' : null,
keypress: true,
selector: base ? '#' + base : null,
effect: 'none',
speed: 'none',
method: 'replaceWith',
progress: {
type: 'throbber',
message: Drupal.t('Please wait...')
},
submit: {
js: true
}
};
$.extend(this, defaults, element_settings);
/**
* @type {Drupal.AjaxCommands}
*/
this.commands = new Drupal.AjaxCommands();
/**
* @type {bool|number}
*/
this.instanceIndex = false;
// @todo Remove this after refactoring the PHP code to:
// - Call this 'selector'.
// - Include the '#' for ID-based selectors.
// - Support non-ID-based selectors.
if (this.wrapper) {
/**
* @type {string}
*/
this.wrapper = '#' + this.wrapper;
}
/**
* @type {HTMLElement}
*/
this.element = element;
/**
* @type {Drupal.Ajax~element_settings}
*/
this.element_settings = element_settings;
// If there isn't a form, jQuery.ajax() will be used instead, allowing us to
// bind Ajax to links as well.
if (this.element && this.element.form) {
/**
* @type {jQuery}
*/
this.$form = $(this.element.form);
}
// If no Ajax callback URL was given, use the link href or form action.
if (!this.url) {
var $element = $(this.element);
if ($element.is('a')) {
this.url = $element.attr('href');
}
else if (this.element && element.form) {
this.url = this.$form.attr('action');
}
}
// Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
// the server detect when it needs to degrade gracefully.
// There are four scenarios to check for:
// 1. /nojs/
// 2. /nojs$ - The end of a URL string.
// 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar).
// 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment).
var originalUrl = this.url;
/**
* Processed Ajax URL.
*
* @type {string}
*/
this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1');
// If the 'nojs' version of the URL is trusted, also trust the 'ajax'
// version.
if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
drupalSettings.ajaxTrustedUrl[this.url] = true;
}
// Set the options for the ajaxSubmit function.
// The 'this' variable will not persist inside of the options object.
var ajax = this;
/**
* Options for the jQuery.ajax function.
*
* @name Drupal.Ajax#options
*
* @type {object}
*
* @prop {string} url
* Ajax URL to be called.
* @prop {object} data
* Ajax payload.
* @prop {function} beforeSerialize
* Implement jQuery beforeSerialize function to call
* {@link Drupal.Ajax#beforeSerialize}.
* @prop {function} beforeSubmit
* Implement jQuery beforeSubmit function to call
* {@link Drupal.Ajax#beforeSubmit}.
* @prop {function} beforeSend
* Implement jQuery beforeSend function to call
* {@link Drupal.Ajax#beforeSend}.
* @prop {function} success
* Implement jQuery success function to call
* {@link Drupal.Ajax#success}.
* @prop {function} complete
* Implement jQuery success function to clean up ajax state and trigger an
* error if needed.
* @prop {string} dataType='json'
* Type of the response expected.
* @prop {string} type='POST'
* HTTP method to use for the Ajax request.
*/
ajax.options = {
url: ajax.url,
data: ajax.submit,
beforeSerialize: function (element_settings, options) {
return ajax.beforeSerialize(element_settings, options);
},
beforeSubmit: function (form_values, element_settings, options) {
ajax.ajaxing = true;
return ajax.beforeSubmit(form_values, element_settings, options);
},
beforeSend: function (xmlhttprequest, options) {
ajax.ajaxing = true;
return ajax.beforeSend(xmlhttprequest, options);
},
success: function (response, status, xmlhttprequest) {
// Sanity check for browser support (object expected).
// When using iFrame uploads, responses must be returned as a string.
if (typeof response === 'string') {
response = $.parseJSON(response);
}
// Prior to invoking the response's commands, verify that they can be
// trusted by checking for a response header. See
// \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details.
// - Empty responses are harmless so can bypass verification. This
// avoids an alert message for server-generated no-op responses that
// skip Ajax rendering.
// - Ajax objects with trusted URLs (e.g., ones defined server-side via
// #ajax) can bypass header verification. This is especially useful
// for Ajax with multipart forms. Because IFRAME transport is used,
// the response headers cannot be accessed for verification.
if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
var customMessage = Drupal.t('The response failed verification so will not be processed.');
return ajax.error(xmlhttprequest, ajax.url, customMessage);
}
}
return ajax.success(response, status);
},
complete: function (xmlhttprequest, status) {
ajax.ajaxing = false;
if (status === 'error' || status === 'parsererror') {
return ajax.error(xmlhttprequest, ajax.url);
}
},
dataType: 'json',
type: 'POST'
};
if (element_settings.dialog) {
ajax.options.data.dialogOptions = element_settings.dialog;
}
// Ensure that we have a valid URL by adding ? when no query parameter is
// yet available, otherwise append using &.
if (ajax.options.url.indexOf('?') === -1) {
ajax.options.url += '?';
}
else {
ajax.options.url += '&';
}
ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=drupal_' + (element_settings.dialogType || 'ajax');
// Bind the ajaxSubmit function to the element event.
$(ajax.element).on(element_settings.event, function (event) {
if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) {
throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url}));
}
return ajax.eventResponse(this, event);
});
// If necessary, enable keyboard submission so that Ajax behaviors
// can be triggered through keyboard input as well as e.g. a mousedown
// action.
if (element_settings.keypress) {
$(ajax.element).on('keypress', function (event) {
return ajax.keypressResponse(this, event);
});
}
// If necessary, prevent the browser default action of an additional event.
// For example, prevent the browser default action of a click, even if the
// Ajax behavior binds to mousedown.
if (element_settings.prevent) {
$(ajax.element).on(element_settings.prevent, false);
}
};
/**
* URL query attribute to indicate the wrapper used to render a request.
*
* The wrapper format determines how the HTML is wrapped, for example in a
* modal dialog.
*
* @const {string}
*
* @default
*/
Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
/**
* Request parameter to indicate that a request is a Drupal Ajax request.
*
* @const {string}
*
* @default
*/
Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
/**
* Execute the ajax request.
*
* Allows developers to execute an Ajax request manually without specifying
* an event to respond to.
*
* @return {object}
* Returns the jQuery.Deferred object underlying the Ajax request. If
* pre-serialization fails, the Deferred will be returned in the rejected
* state.
*/
Drupal.Ajax.prototype.execute = function () {
// Do not perform another ajax command if one is already in progress.
if (this.ajaxing) {
return;
}
try {
this.beforeSerialize(this.element, this.options);
// Return the jqXHR so that external code can hook into the Deferred API.
return $.ajax(this.options);
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
this.ajaxing = false;
window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message);
// For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
// so that calling code can take appropriate action.
return $.Deferred().reject();
}
};
/**
* Handle a key press.
*
* The Ajax object will, if instructed, bind to a key press response. This
* will test to see if the key press is valid to trigger this event and
* if it is, trigger it for us and prevent other keypresses from triggering.
* In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
* and 32. RETURN is often used to submit a form when in a textfield, and
* SPACE is often used to activate an element without submitting.
*
* @param {HTMLElement} element
* Element the event was triggered on.
* @param {jQuery.Event} event
* Triggered event.
*/
Drupal.Ajax.prototype.keypressResponse = function (element, event) {
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Detect enter key and space bar and allow the standard response for them,
// except for form elements of type 'text', 'tel', 'number' and 'textarea',
// where the spacebar activation causes inappropriate activation if
// #ajax['keypress'] is TRUE. On a text-type widget a space should always
// be a space.
if (event.which === 13 || (event.which === 32 && element.type !== 'text' &&
element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number')) {
event.preventDefault();
event.stopPropagation();
$(ajax.element_settings.element).trigger(ajax.element_settings.event);
}
};
/**
* Handle an event that triggers an Ajax response.
*
* When an event that triggers an Ajax response happens, this method will
* perform the actual Ajax call. It is bound to the event using
* bind() in the constructor, and it uses the options specified on the
* Ajax object.
*
* @param {HTMLElement} element
* Element the event was triggered on.
* @param {jQuery.Event} event
* Triggered event.
*/
Drupal.Ajax.prototype.eventResponse = function (element, event) {
event.preventDefault();
event.stopPropagation();
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Do not perform another Ajax command if one is already in progress.
if (ajax.ajaxing) {
return;
}
try {
if (ajax.$form) {
// If setClick is set, we must set this to ensure that the button's
// value is passed.
if (ajax.setClick) {
// Mark the clicked button. 'form.clk' is a special variable for
// ajaxSubmit that tells the system which element got clicked to
// trigger the submit. Without it there would be no 'op' or
// equivalent.
element.form.clk = element;
}
ajax.$form.ajaxSubmit(ajax.options);
}
else {
ajax.beforeSerialize(ajax.element, ajax.options);
$.ajax(ajax.options);
}
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
ajax.ajaxing = false;
window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message);
}
};
/**
* Handler for the form serialization.
*
* Runs before the beforeSend() handler (see below), and unlike that one, runs
* before field data is collected.
*
* @param {object} [element]
* Ajax object's `element_settings`.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSerialize = function (element, options) {
// Allow detaching behaviors to update field values before collecting them.
// This is only needed when field values are added to the POST data, so only
// when there is a form such that this.$form.ajaxSubmit() is used instead of
// $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
// isn't called, but don't rely on that: explicitly check this.$form.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
}
// Inform Drupal that this is an AJAX request.
options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
// Allow Drupal to return new JavaScript and CSS files to load without
// returning the ones already loaded.
// @see \Drupal\Core\Theme\AjaxBasePageNegotiator
// @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
// @see system_js_settings_alter()
var pageState = drupalSettings.ajaxPageState;
options.data['ajax_page_state[theme]'] = pageState.theme;
options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
options.data['ajax_page_state[libraries]'] = pageState.libraries;
};
/**
* Modify form values prior to form submission.
*
* @param {Array.<object>} form_values
* Processed form values.
* @param {jQuery} element
* The form node as a jQuery object.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
// This function is left empty to make it simple to override for modules
// that wish to add functionality here.
};
/**
* Prepare the Ajax request before it is sent.
*
* @param {XMLHttpRequest} xmlhttprequest
* Native Ajax object.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) {
// For forms without file inputs, the jQuery Form plugin serializes the
// form values, and then calls jQuery's $.ajax() function, which invokes
// this handler. In this circumstance, options.extraData is never used. For
// forms with file inputs, the jQuery Form plugin uses the browser's normal
// form submission mechanism, but captures the response in a hidden IFRAME.
// In this circumstance, it calls this handler first, and then appends
// hidden fields to the form to submit the values in options.extraData.
// There is no simple way to know which submission mechanism will be used,
// so we add to extraData regardless, and allow it to be ignored in the
// former case.
if (this.$form) {
options.extraData = options.extraData || {};
// Let the server know when the IFRAME submission mechanism is used. The
// server can use this information to wrap the JSON response in a
// TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
options.extraData.ajax_iframe_upload = '1';
// The triggering element is about to be disabled (see below), but if it
// contains a value (e.g., a checkbox, textfield, select, etc.), ensure
// that value is included in the submission. As per above, submissions
// that use $.ajax() are already serialized prior to the element being
// disabled, so this is only needed for IFRAME submissions.
var v = $.fieldValue(this.element);
if (v !== null) {
options.extraData[this.element.name] = v;
}
}
// Disable the element that received the change to prevent user interface
// interaction while the Ajax request is in progress. ajax.ajaxing prevents
// the element from triggering a new request, but does not prevent the user
// from changing its value.
$(this.element).prop('disabled', true);
if (!this.progress || !this.progress.type) {
return;
}
// Insert progress indicator.
var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase();
if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
this[progressIndicatorMethod].call(this);
}
};
/**
* Sets the progress bar progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorBar = function () {
var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop);
if (this.progress.message) {
progressBar.setProgress(-1, this.progress.message);
}
if (this.progress.url) {
progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
}
this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
this.progress.object = progressBar;
$(this.element).after(this.progress.element);
};
/**
* Sets the throbber progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
if (this.progress.message) {
this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>');
}
$(this.element).after(this.progress.element);
};
/**
* Sets the fullscreen progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen"> </div>');
$('body').after(this.progress.element);
};
/**
* Handler for the form redirection completion.
*
* @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
* Drupal Ajax response.
* @param {number} status
* XMLHttpRequest status.
*/
Drupal.Ajax.prototype.success = function (response, status) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
$(this.element).prop('disabled', false);
// Save element's ancestors tree so if the element is removed from the dom
// we can try to refocus one of its parents. Using addBack reverse the
// result array, meaning that index 0 is the highest parent in the hierarchy
// in this situation it is usually a <form> element.
var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray();
// Track if any command is altering the focus so we can avoid changing the
// focus set by the Ajax command.
var focusChanged = false;
for (var i in response) {
if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
this.commands[response[i].command](this, response[i], status);
if (response[i].command === 'invoke' && response[i].method === 'focus') {
focusChanged = true;
}
}
}
// If the focus hasn't be changed by the ajax commands, try to refocus the
// triggering element or one of its parents if that element does not exist
// anymore.
if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) {
var target = false;
for (var n = elementParents.length - 1; !target && n > 0; n--) {
target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]');
}
if (target) {
$(target).trigger('focus');
}
}
// Reattach behaviors, if they were detached in beforeSerialize(). The
// attachBehaviors() called on the new content from processing the response
// commands is not sufficient, because behaviors from the entire form need
// to be reattached.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
// Remove any response-specific settings so they don't get used on the next
// call by mistake.
this.settings = null;
};
/**
* Build an effect object to apply an effect when adding new HTML.
*
* @param {object} response
* Drupal Ajax response.
* @param {string} [response.effect]
* Override the default value of {@link Drupal.Ajax#element_settings}.
* @param {string|number} [response.speed]
* Override the default value of {@link Drupal.Ajax#element_settings}.
*
* @return {object}
* Returns an object with `showEffect`, `hideEffect` and `showSpeed`
* properties.
*/
Drupal.Ajax.prototype.getEffect = function (response) {
var type = response.effect || this.effect;
var speed = response.speed || this.speed;
var effect = {};
if (type === 'none') {
effect.showEffect = 'show';
effect.hideEffect = 'hide';
effect.showSpeed = '';
}
else if (type === 'fade') {
effect.showEffect = 'fadeIn';
effect.hideEffect = 'fadeOut';
effect.showSpeed = speed;
}
else {
effect.showEffect = type + 'Toggle';
effect.hideEffect = type + 'Toggle';
effect.showSpeed = speed;
}
return effect;
};
/**
* Handler for the form redirection error.
*
* @param {object} xmlhttprequest
* Native XMLHttpRequest object.
* @param {string} uri
* Ajax Request URI.
* @param {string} [customMessage]
* Extra message to print with the Ajax error.
*/
Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
// Undo hide.
$(this.wrapper).show();
// Re-enable the element.
$(this.element).prop('disabled', false);
// Reattach behaviors, if they were detached in beforeSerialize().
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
};
/**
* @typedef {object} Drupal.AjaxCommands~commandDefinition
*
* @prop {string} command
* @prop {string} [method]
* @prop {string} [selector]
* @prop {string} [data]
* @prop {object} [settings]
* @prop {bool} [asterisk]
* @prop {string} [text]
* @prop {string} [title]
* @prop {string} [url]
* @prop {object} [argument]
* @prop {string} [name]
* @prop {string} [value]
* @prop {string} [old]
* @prop {string} [new]
* @prop {bool} [merge]
* @prop {Array} [args]
*
* @see Drupal.AjaxCommands
*/
/**
* Provide a series of commands that the client will perform.
*
* @constructor
*/
Drupal.AjaxCommands = function () {};
Drupal.AjaxCommands.prototype = {
/**
* Command to insert new content into the DOM.
*
* @param {Drupal.Ajax} ajax
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.data
* The data to use with the jQuery method.
* @param {string} [response.method]
* The jQuery DOM manipulation method to be used.
* @param {string} [response.selector]
* A optional jQuery selector string.
* @param {object} [response.settings]
* An optional array of settings that will be used.
* @param {number} [status]
* The XMLHttpRequest status.
*/
insert: function (ajax, response, status) {
// Get information from the response. If it is not there, default to
// our presets.
var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
var method = response.method || ajax.method;
var effect = ajax.getEffect(response);
var settings;
// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly interpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('<div></div>').replaceWith(response.data).
var $new_content_wrapped = $('<div></div>').html(response.data);
var $new_content = $new_content_wrapped.contents();
// For legacy reasons, the effects processing code assumes that
// $new_content consists of a single top-level element. Also, it has not
// been sufficiently tested whether attachBehaviors() can be successfully
// called with a context object that includes top-level text nodes.
// However, to give developers full control of the HTML appearing in the
// page, and to enable Ajax content to be inserted in places where <div>
// elements are not allowed (e.g., within <table>, <tr>, and <span>
// parents), we check if the new content satisfies the requirement
// of a single top-level element, and only use the container <div> created
// above when it doesn't. For more information, please see
// https://www.drupal.org/node/736066.
if ($new_content.length !== 1 || $new_content.get(0).nodeType !== 1) {
$new_content = $new_content_wrapped;
}
// If removing content from the wrapper, detach behaviors first.
switch (method) {
case 'html':
case 'replaceWith':
case 'replaceAll':
case 'empty':
case 'remove':
settings = response.settings || ajax.settings || drupalSettings;
Drupal.detachBehaviors($wrapper.get(0), settings);
}
// Add the new content to the page.
$wrapper[method]($new_content);
// Immediately hide the new content if we're using any effects.
if (effect.showEffect !== 'show') {
$new_content.hide();
}
// Determine which effect to use and what content will receive the
// effect, then show the new content.
if ($new_content.find('.ajax-new-content').length > 0) {
$new_content.find('.ajax-new-content').hide();
$new_content.show();
$new_content.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
}
else if (effect.showEffect !== 'show') {
$new_content[effect.showEffect](effect.showSpeed);
}
// Attach all JavaScript behaviors to the new content, if it was
// successfully added to the page, this if statement allows
// `#ajax['wrapper']` to be optional.
if ($new_content.parents('html').length > 0) {
// Apply any settings from the returned JSON if available.
settings = response.settings || ajax.settings || drupalSettings;
Drupal.attachBehaviors($new_content.get(0), settings);
}
},
/**
* Command to remove a chunk from the page.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {object} [response.settings]
* An optional array of settings that will be used.
* @param {number} [status]
* The XMLHttpRequest status.
*/
remove: function (ajax, response, status) {
var settings = response.settings || ajax.settings || drupalSettings;
$(response.selector).each(function () {
Drupal.detachBehaviors(this, settings);
})
.remove();
},
/**
* Command to mark a chunk changed.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The JSON response object from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {bool} [response.asterisk]
* An optional CSS selector. If specified, an asterisk will be
* appended to the HTML inside the provided selector.
* @param {number} [status]
* The request status.
*/
changed: function (ajax, response, status) {
var $element = $(response.selector);
if (!$element.hasClass('ajax-changed')) {
$element.addClass('ajax-changed');
if (response.asterisk) {
$element.find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> ');
}
}
},
/**
* Command to provide an alert.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The JSON response from the Ajax request.
* @param {string} response.text
* The text that will be displayed in an alert dialog.
* @param {number} [status]
* The XMLHttpRequest status.
*/
alert: function (ajax, response, status) {
window.alert(response.text, response.title);
},
/**
* Command to set the window.location, redirecting the browser.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.url
* The URL to redirect to.
* @param {number} [status]
* The XMLHttpRequest status.
*/
redirect: function (ajax, response, status) {
window.location = response.url;
},
/**
* Command to provide the jQuery css() function.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {object} response.argument
* An array of key/value pairs to set in the CSS for the selector.
* @param {number} [status]
* The XMLHttpRequest status.
*/
css: function (ajax, response, status) {
$(response.selector).css(response.argument);
},
/**
* Command to set the settings used for other commands in this response.
*
* This method will also remove expired `drupalSettings.ajax` settings.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {bool} response.merge
* Determines whether the additional settings should be merged to the
* global settings.
* @param {object} response.settings
* Contains additional settings to add to the global settings.
* @param {number} [status]
* The XMLHttpRequest status.
*/
settings: function (ajax, response, status) {
var ajaxSettings = drupalSettings.ajax;
// Clean up drupalSettings.ajax.
if (ajaxSettings) {
Drupal.ajax.expired().forEach(function (instance) {
// If the Ajax object has been created through drupalSettings.ajax
// it will have a selector. When there is no selector the object
// has been initialized with a special class name picked up by the
// Ajax behavior.
if (instance.selector) {
var selector = instance.selector.replace('#', '');
if (selector in ajaxSettings) {
delete ajaxSettings[selector];
}
}
});
}
if (response.merge) {
$.extend(true, drupalSettings, response.settings);
}
else {
ajax.settings = response.settings;
}
},
/**
* Command to attach data using jQuery's data API.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.name
* The name or key (in the key value pair) of the data attached to this
* selector.
* @param {string} response.selector
* A jQuery selector string.
* @param {string|object} response.value
* The value of to be attached.
* @param {number} [status]
* The XMLHttpRequest status.
*/
data: function (ajax, response, status) {
$(response.selector).data(response.name, response.value);
},
/**
* Command to apply a jQuery method.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {Array} response.args
* An array of arguments to the jQuery method, if any.
* @param {string} response.method
* The jQuery method to invoke.
* @param {string} response.selector
* A jQuery selector string.
* @param {number} [status]
* The XMLHttpRequest status.
*/
invoke: function (ajax, response, status) {
var $element = $(response.selector);
$element[response.method].apply($element, response.args);
},
/**
* Command to restripe a table.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {number} [status]
* The XMLHttpRequest status.
*/
restripe: function (ajax, response, status) {
// :even and :odd are reversed because jQuery counts from 0 and
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$(response.selector).find('> tbody > tr:visible, > tr:visible')
.removeClass('odd even')
.filter(':even').addClass('odd').end()
.filter(':odd').addClass('even');
},
/**
* Command to update a form's build ID.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.old
* The old form build ID.
* @param {string} response.new
* The new form build ID.
* @param {number} [status]
* The XMLHttpRequest status.
*/
update_build_id: function (ajax, response, status) {
$('input[name="form_build_id"][value="' + response.old + '"]').val(response.new);
},
/**
* Command to add css.
*
* Uses the proprietary addImport method if available as browsers which
* support that method ignore @import statements in dynamically added
* stylesheets.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.data
* A string that contains the styles to be added.
* @param {number} [status]
* The XMLHttpRequest status.
*/
add_css: function (ajax, response, status) {
// Add the styles in the normal way.
$('head').prepend(response.data);
// Add imports in the styles using the addImport method if available.
var match;
var importMatch = /^@import url\("(.*)"\);$/igm;
if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
importMatch.lastIndex = 0;
do {
match = importMatch.exec(response.data);
document.styleSheets[0].addImport(match[1]);
} while (match);
}
}
};
})(jQuery, window, Drupal, drupalSettings);
;
/**
* @file
* Extends methods from core/misc/ajax.js.
*/
(function ($, window, Drupal, drupalSettings) {
/**
* Attempts to find the closest glyphicon progress indicator.
*
* @param {jQuery|Element} element
* A DOM element.
*
* @returns {jQuery}
* A jQuery object.
*/
Drupal.Ajax.prototype.findGlyphicon = function (element) {
return $(element).closest('.form-item').find('.ajax-progress.glyphicon')
};
/**
* Starts the spinning of the glyphicon progress indicator.
*
* @param {jQuery|Element} element
* A DOM element.
* @param {string} [message]
* An optional message to display (tooltip) for the progress.
*
* @returns {jQuery}
* A jQuery object.
*/
Drupal.Ajax.prototype.glyphiconStart = function (element, message) {
var $glyphicon = this.findGlyphicon(element);
if ($glyphicon[0]) {
$glyphicon.addClass('glyphicon-spin');
// Add any message as a tooltip to the glyphicon.
if (drupalSettings.bootstrap.tooltip_enabled) {
$glyphicon
.removeAttr('data-toggle')
.removeAttr('data-original-title')
.removeAttr('title')
.tooltip('destroy')
;
if (message) {
$glyphicon.attr('data-toggle', 'tooltip').attr('title', message).tooltip();
}
}
// Append a message for screen readers.
if (message) {
$glyphicon.parent().append('<div class="sr-only message">' + message + '</div>');
}
}
return $glyphicon;
};
/**
* Stop the spinning of a glyphicon progress indicator.
*
* @param {jQuery|Element} element
* A DOM element.
*/
Drupal.Ajax.prototype.glyphiconStop = function (element) {
var $glyphicon = this.findGlyphicon(element);
if ($glyphicon[0]) {
$glyphicon.removeClass('glyphicon-spin');
if (drupalSettings.bootstrap.tooltip_enabled) {
$glyphicon
.removeAttr('data-toggle')
.removeAttr('data-original-title')
.removeAttr('title')
.tooltip('destroy')
;
}
}
};
/**
* Sets the throbber progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
var $element = $(this.element);
// Find an existing glyphicon progress indicator.
var $glyphicon = this.glyphiconStart($element, this.progress.message);
if ($glyphicon[0]) {
this.progress.element = $glyphicon.parent();
this.progress.glyphicon = true;
return;
}
// Otherwise, add a glyphicon throbber after the element.
if (!this.progress.element) {
this.progress.element = $(Drupal.theme('ajaxThrobber'));
}
if (this.progress.message) {
this.progress.element.after('<div class="message">' + this.progress.message + '</div>');
}
// If element is an input DOM element type (not :input), append after.
if ($element.is('input')) {
$element.after(this.progress.element);
}
// Otherwise append the throbber inside the element.
else {
$element.append(this.progress.element);
}
};
/**
* Handler for the form redirection completion.
*
* @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
* @param {number} status
*/
Drupal.Ajax.prototype.success = function (response, status) {
if (this.progress.element) {
// Stop a glyphicon throbber.
if (this.progress.glyphicon) {
this.glyphiconStop(this.progress.element);
}
// Remove the progress element.
else {
this.progress.element.remove();
}
// Remove any message set.
this.progress.element.parent().find('.message').remove();
}
// --------------------------------------------------------
// Everything below is from core/misc/ajax.js.
// --------------------------------------------------------
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
$(this.element).prop('disabled', false);
// Save element's ancestors tree so if the element is removed from the dom
// we can try to refocus one of its parents. Using addBack reverse the
// result array, meaning that index 0 is the highest parent in the hierarchy
// in this situation it is usually a <form> element.
var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray();
// Track if any command is altering the focus so we can avoid changing the
// focus set by the Ajax command.
var focusChanged = false;
for (var i in response) {
if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
this.commands[response[i].command](this, response[i], status);
if (response[i].command === 'invoke' && response[i].method === 'focus') {
focusChanged = true;
}
}
}
// If the focus hasn't be changed by the ajax commands, try to refocus the
// triggering element or one of its parents if that element does not exist
// anymore.
if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) {
var target = false;
for (var n = elementParents.length - 1; !target && n > 0; n--) {
target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]');
}
if (target) {
$(target).trigger('focus');
}
}
// Reattach behaviors, if they were detached in beforeSerialize(). The
// attachBehaviors() called on the new content from processing the response
// commands is not sufficient, because behaviors from the entire form need
// to be reattached.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
// Remove any response-specific settings so they don't get used on the next
// call by mistake.
this.settings = null;
};
})(jQuery, this, Drupal, drupalSettings);
;
/**
* @file
* Bootstrap Modals.
*/
(function ($, Drupal, Bootstrap) {
"use strict";
/**
* Extend the Bootstrap Modal plugin constructor class.
*/
Bootstrap.extendPlugin('modal', function (settings) {
return {
DEFAULTS: {
animation: !!settings.modal_animation,
backdrop: settings.modal_backdrop === 'static' ? 'static' : !!settings.modal_backdrop,
keyboard: !!settings.modal_keyboard,
show: !!settings.modal_show,
size: settings.modal_size
}
};
});
/**
* Replace the Bootstrap Modal jQuery plugin definition.
*
* Replacing this is needed so that the "option" method can return values.
*/
Bootstrap.replacePlugin('modal', function () {
var Modal = this;
// Extract the arguments.
var args = Array.prototype.slice.call(arguments, 1);
// Modal jQuery Plugin Definition.
return function (option, _relatedTarget) {
var ret = void(0);
this.each(function () {
var $this = $(this);
var data = $this.data('bs.modal');
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option);
if (!data) $this.data('bs.modal', (data = new Modal(this, options)));
if (typeof option == 'string') ret = data[option].apply(data, args);
else if (options.show) data.show(_relatedTarget);
});
// If just one element and there was a result returned for the option passed,
// then return the result. Otherwise, just return the jQuery object.
return this.length === 1 && ret !== void(0) ? ret : this;
}
});
/**
* Extend Drupal theming functions.
*/
$.extend(Drupal.theme, /** @lend Drupal.theme */ {
/**
* Theme function for a Bootstrap Modal.
*
* @param {object}[variables]
* An object with the following keys:
* - title: The name of the tab.
*
* @return {string}
* The HTML for the modal.
*/
bootstrapModal: function (variables) {
var settings = drupalSettings.bootstrap || {};
var defaults = {
body: '',
closeButton: true,
description: {
content: null,
position: 'before'
},
footer: '',
id: 'drupal-modal',
size: settings.modal_size ? settings.modal_size : '',
title: Drupal.t('Loading...')
};
variables = $.extend(true, {}, defaults, variables);
var output = '';
// Build the modal wrapper.
var classes = ['modal'];
if (settings.modal_animation) {
classes.push('fade');
}
output += '<div id="' + variables.id + '" class="' + classes.join(' ') + '" tabindex="-1" role="dialog">';
// Build the modal-dialog wrapper.
var dialogClasses = ['modal-dialog'];
if (variables.size) {
// @todo This should really be a clean CSS class method instead.
dialogClasses.push(Drupal.checkPlain(variables.size));
}
output += '<div class="' + dialogClasses.join(' ') + '" role="document">';
// Build the modal-content wrapper.
output += '<div class="modal-content">';
// Build the header wrapper and title.
output += Drupal.theme.bootstrapModalHeader(variables.title, variables.closeButton);
// Build the body.
output += Drupal.theme.bootstrapModalBody(variables.id + '--body', variables.body, variables.description);
// Build the footer.
output += Drupal.theme.bootstrapModalFooter(variables.footer);
// Close the modal-content wrapper.
output += '</div>';
// Close the modal-dialog wrapper.
output += '</div>';
// Close the modal wrapper.
output += '</div>';
// Return the constructed modal.
return output;
},
/**
* Theme function for a Bootstrap Modal body markup.
*
* @param {string} id
* A unique ID for the modal body div.
* @param {string} body
* The HTML markup to place in the body.
* @param {string|object} description
* A description to show. Can either be a string or an object with the
* following key/value pairs:
* - content: The description value.
* - position: (optional) A display setting that can have these values:
* - before: The description is displayed before the body. This is the
* default value.
* - after: The description is display after the body.
* - invisible: The description is displayed after the element, hidden
* visually but available to screen readers.
*
* @return {string}
* The HTML for the modal close button.
*/
bootstrapModalBody: function (id, body, description) {
var output = '';
output += '<div id="' + id + '" class="modal-body">';
if (!description || !$.isPlainObject(description)) {
description = { content: description};
}
description = $.extend({ position: 'before' }, description);
var descriptionClasses = ['help-block'];
if (description.content && description.position === 'invisible') {
descriptionClasses.push('sr-only');
}
if (description.content && description.position === 'before') {
output += '<p class="' + descriptionClasses.join(' ') + '">' + description.content + '</p>';
}
output += body;
if (description.content && (description.position === 'after' || description.position === 'invisible')) {
output += '<p class="' + descriptionClasses.join(' ') + '">' + description.content + '</p>';
}
output += '</div>';
return output;
},
/**
* Theme function for a Bootstrap Modal close button.
*
* @return {string}
* The HTML for the modal close button.
*/
bootstrapModalClose: function () {
return '<button type="button" class="close" data-dismiss="modal" aria-label="' + Drupal.t('Close') + '"><span aria-hidden="true">×</span></button>';
},
/**
* Theme function for a Bootstrap Modal footer.
*
* @param {string} [footer]
* The HTML markup to place in the footer.
* @param {boolean} [force]
* Flag to force the rendering of the footer.
*
* @return {string}
* The HTML for the modal footer.
*/
bootstrapModalFooter: function (footer, force) {
return footer || force ? '<div class="modal-footer">' + (footer || '') + '</div>' : '';
},
/**
* Theme function for a Bootstrap Modal header.
*
* @param {string} [title]
* The title for the header.
* @param {boolean} [closeButton]
* Flag indicating whether or not to show the close button in the header.
*
* @return {string}
* The HTML for the modal header.
*/
bootstrapModalHeader: function (title, closeButton) {
var output = '';
if (title) {
closeButton = closeButton !== void(0) ? closeButton : true;
output += '<div class="modal-header">';
if (closeButton) {
output += Drupal.theme.bootstrapModalClose();
}
output += '<h4 class="modal-title">' + Drupal.checkPlain(title) + '</h4>';
output += '</div>';
}
return output;
}
})
})(window.jQuery, window.Drupal, window.Drupal.bootstrap);
;
/**
* @file
* Dialog API inspired by HTML5 dialog element.
*
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#the-dialog-element
*/
(function ($, Drupal, drupalSettings) {
'use strict';
/**
* Default dialog options.
*
* @type {object}
*
* @prop {bool} [autoOpen=true]
* @prop {string} [dialogClass='']
* @prop {string} [buttonClass='button']
* @prop {string} [buttonPrimaryClass='button--primary']
* @prop {function} close
*/
drupalSettings.dialog = {
autoOpen: true,
dialogClass: '',
// Drupal-specific extensions: see dialog.jquery-ui.js.
buttonClass: 'button',
buttonPrimaryClass: 'button--primary',
// When using this API directly (when generating dialogs on the client
// side), you may want to override this method and do
// `jQuery(event.target).remove()` as well, to remove the dialog on
// closing.
close: function (event) {
Drupal.detachBehaviors(event.target, null, 'unload');
}
};
/**
* @typedef {object} Drupal.dialog~dialogDefinition
*
* @prop {boolean} open
* Is the dialog open or not.
* @prop {*} returnValue
* Return value of the dialog.
* @prop {function} show
* Method to display the dialog on the page.
* @prop {function} showModal
* Method to display the dialog as a modal on the page.
* @prop {function} close
* Method to hide the dialog from the page.
*/
/**
* Polyfill HTML5 dialog element with jQueryUI.
*
* @param {HTMLElement} element
* @param {object} options
* jQuery UI options to be passed to the dialog.
*
* @return {Drupal.dialog~dialogDefinition}
*/
Drupal.dialog = function (element, options) {
var $element = $(element);
function openDialog(settings) {
settings = $.extend({}, drupalSettings.dialog, options, settings);
// Trigger a global event to allow scripts to bind events to the dialog.
$(window).trigger('dialog:beforecreate', [dialog, $element, settings]);
$element
.modal(settings)
.on('shown.bs.modal.drupal', function () {
dialog.open = true;
$(window).trigger('dialog:aftercreate', [dialog, $element, settings]);
})
;
}
function closeDialog(value) {
$(window).trigger('dialog:beforeclose', [dialog, $element]);
$element
.on('hidden.bs.modal.drupal', function () {
dialog.returnValue = value;
dialog.open = false;
$(window).trigger('dialog:afterclose', [dialog, $element]);
})
.modal('hide');
}
var dialog = {
open: false,
returnValue: void(0),
show: function () {
openDialog({show: false});
},
showModal: function () {
openDialog({show: true});
},
close: closeDialog
};
return dialog;
};
})(jQuery, Drupal, drupalSettings);
;
/**
* @file
* Attaches behavior for the Quick Edit module.
*
* Everything happens asynchronously, to allow for:
* - dynamically rendered contextual links
* - asynchronously retrieved (and cached) per-field in-place editing metadata
* - asynchronous setup of in-place editable field and "Quick edit" link.
*
* To achieve this, there are several queues:
* - fieldsMetadataQueue: fields whose metadata still needs to be fetched.
* - fieldsAvailableQueue: queue of fields whose metadata is known, and for
* which it has been confirmed that the user has permission to edit them.
* However, FieldModels will only be created for them once there's a
* contextual link for their entity: when it's possible to initiate editing.
* - contextualLinksQueue: queue of contextual links on entities for which it
* is not yet known whether the user has permission to edit at >=1 of them.
*/
(function ($, _, Backbone, Drupal, drupalSettings, JSON, storage) {
'use strict';
var options = $.extend(drupalSettings.quickedit,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
quickEdit: Drupal.t('Quick edit')
}
}
);
/**
* Tracks fields without metadata. Contains objects with the following keys:
* - DOM el
* - String fieldID
* - String entityID
*/
var fieldsMetadataQueue = [];
/**
* Tracks fields ready for use. Contains objects with the following keys:
* - DOM el
* - String fieldID
* - String entityID
*/
var fieldsAvailableQueue = [];
/**
* Tracks contextual links on entities. Contains objects with the following
* keys:
* - String entityID
* - DOM el
* - DOM region
*/
var contextualLinksQueue = [];
/**
* Tracks how many instances exist for each unique entity. Contains key-value
* pairs:
* - String entityID
* - Number count
*/
var entityInstancesTracker = {};
/**
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.quickedit = {
attach: function (context) {
// Initialize the Quick Edit app once per page load.
$('body').once('quickedit-init').each(initQuickEdit);
// Find all in-place editable fields, if any.
var $fields = $(context).find('[data-quickedit-field-id]').once('quickedit');
if ($fields.length === 0) {
return;
}
// Process each entity element: identical entities that appear multiple
// times will get a numeric identifier, starting at 0.
$(context).find('[data-quickedit-entity-id]').once('quickedit').each(function (index, entityElement) {
processEntity(entityElement);
});
// Process each field element: queue to be used or to fetch metadata.
// When a field is being rerendered after editing, it will be processed
// immediately. New fields will be unable to be processed immediately,
// but will instead be queued to have their metadata fetched, which occurs
// below in fetchMissingMetaData().
$fields.each(function (index, fieldElement) {
processField(fieldElement);
});
// Entities and fields on the page have been detected, try to set up the
// contextual links for those entities that already have the necessary
// meta- data in the client-side cache.
contextualLinksQueue = _.filter(contextualLinksQueue, function (contextualLink) {
return !initializeEntityContextualLink(contextualLink);
});
// Fetch metadata for any fields that are queued to retrieve it.
fetchMissingMetadata(function (fieldElementsWithFreshMetadata) {
// Metadata has been fetched, reprocess fields whose metadata was
// missing.
_.each(fieldElementsWithFreshMetadata, processField);
// Metadata has been fetched, try to set up more contextual links now.
contextualLinksQueue = _.filter(contextualLinksQueue, function (contextualLink) {
return !initializeEntityContextualLink(contextualLink);
});
});
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
deleteContainedModelsAndQueues($(context));
}
}
};
/**
*
* @namespace
*/
Drupal.quickedit = {
/**
* A {@link Drupal.quickedit.AppView} instance.
*/
app: null,
/**
* @type {object}
*
* @prop {Array.<Drupal.quickedit.EntityModel>} entities
* @prop {Array.<Drupal.quickedit.FieldModel>} fields
*/
collections: {
// All in-place editable entities (Drupal.quickedit.EntityModel) on the
// page.
entities: null,
// All in-place editable fields (Drupal.quickedit.FieldModel) on the page.
fields: null
},
/**
* In-place editors will register themselves in this object.
*
* @namespace
*/
editors: {},
/**
* Per-field metadata that indicates whether in-place editing is allowed,
* which in-place editor should be used, etc.
*
* @namespace
*/
metadata: {
/**
* Check if a field exists in storage.
*
* @param {string} fieldID
* The field id to check.
*
* @return {bool}
* Whether it was found or not.
*/
has: function (fieldID) {
return storage.getItem(this._prefixFieldID(fieldID)) !== null;
},
/**
* Add metadata to a field id.
*
* @param {string} fieldID
* The field ID to add data to.
* @param {object} metadata
* Metadata to add.
*/
add: function (fieldID, metadata) {
storage.setItem(this._prefixFieldID(fieldID), JSON.stringify(metadata));
},
/**
* Get a key from a field id.
*
* @param {string} fieldID
* The field ID to check.
* @param {string} [key]
* The key to check. If empty, will return all metadata.
*
* @return {object|*}
* The value for the key, if defined. Otherwise will return all metadata
* for the specified field id.
*
*/
get: function (fieldID, key) {
var metadata = JSON.parse(storage.getItem(this._prefixFieldID(fieldID)));
return (typeof key === 'undefined') ? metadata : metadata[key];
},
/**
* Prefix the field id.
*
* @param {string} fieldID
* The field id to prefix.
*
* @return {string}
* A prefixed field id.
*/
_prefixFieldID: function (fieldID) {
return 'Drupal.quickedit.metadata.' + fieldID;
},
/**
* Unprefix the field id.
*
* @param {string} fieldID
* The field id to unprefix.
*
* @return {string}
* An unprefixed field id.
*/
_unprefixFieldID: function (fieldID) {
// Strip "Drupal.quickedit.metadata.", which is 26 characters long.
return fieldID.substring(26);
},
/**
* Intersection calculation.
*
* @param {Array} fieldIDs
* An array of field ids to compare to prefix field id.
*
* @return {Array}
* The intersection found.
*/
intersection: function (fieldIDs) {
var prefixedFieldIDs = _.map(fieldIDs, this._prefixFieldID);
var intersection = _.intersection(prefixedFieldIDs, _.keys(sessionStorage));
return _.map(intersection, this._unprefixFieldID);
}
}
};
// Clear the Quick Edit metadata cache whenever the current user's set of
// permissions changes.
var permissionsHashKey = Drupal.quickedit.metadata._prefixFieldID('permissionsHash');
var permissionsHashValue = storage.getItem(permissionsHashKey);
var permissionsHash = drupalSettings.user.permissionsHash;
if (permissionsHashValue !== permissionsHash) {
if (typeof permissionsHash === 'string') {
_.chain(storage).keys().each(function (key) {
if (key.substring(0, 26) === 'Drupal.quickedit.metadata.') {
storage.removeItem(key);
}
});
}
storage.setItem(permissionsHashKey, permissionsHash);
}
/**
* Detect contextual links on entities annotated by quickedit.
*
* Queue contextual links to be processed.
*
* @param {jQuery.Event} event
* The `drupalContextualLinkAdded` event.
* @param {object} data
* An object containing the data relevant to the event.
*
* @listens event:drupalContextualLinkAdded
*/
$(document).on('drupalContextualLinkAdded', function (event, data) {
if (data.$region.is('[data-quickedit-entity-id]')) {
// If the contextual link is cached on the client side, an entity instance
// will not yet have been assigned. So assign one.
if (!data.$region.is('[data-quickedit-entity-instance-id]')) {
data.$region.once('quickedit');
processEntity(data.$region.get(0));
}
var contextualLink = {
entityID: data.$region.attr('data-quickedit-entity-id'),
entityInstanceID: data.$region.attr('data-quickedit-entity-instance-id'),
el: data.$el[0],
region: data.$region[0]
};
// Set up contextual links for this, otherwise queue it to be set up
// later.
if (!initializeEntityContextualLink(contextualLink)) {
contextualLinksQueue.push(contextualLink);
}
}
});
/**
* Extracts the entity ID from a field ID.
*
* @param {string} fieldID
* A field ID: a string of the format
* `<entity type>/<id>/<field name>/<language>/<view mode>`.
*
* @return {string}
* An entity ID: a string of the format `<entity type>/<id>`.
*/
function extractEntityID(fieldID) {
return fieldID.split('/').slice(0, 2).join('/');
}
/**
* Initialize the Quick Edit app.
*
* @param {HTMLElement} bodyElement
* This document's body element.
*/
function initQuickEdit(bodyElement) {
Drupal.quickedit.collections.entities = new Drupal.quickedit.EntityCollection();
Drupal.quickedit.collections.fields = new Drupal.quickedit.FieldCollection();
// Instantiate AppModel (application state) and AppView, which is the
// controller of the whole in-place editing experience.
Drupal.quickedit.app = new Drupal.quickedit.AppView({
el: bodyElement,
model: new Drupal.quickedit.AppModel(),
entitiesCollection: Drupal.quickedit.collections.entities,
fieldsCollection: Drupal.quickedit.collections.fields
});
}
/**
* Assigns the entity an instance ID.
*
* @param {HTMLElement} entityElement
* A Drupal Entity API entity's DOM element with a data-quickedit-entity-id
* attribute.
*/
function processEntity(entityElement) {
var entityID = entityElement.getAttribute('data-quickedit-entity-id');
if (!entityInstancesTracker.hasOwnProperty(entityID)) {
entityInstancesTracker[entityID] = 0;
}
else {
entityInstancesTracker[entityID]++;
}
// Set the calculated entity instance ID for this element.
var entityInstanceID = entityInstancesTracker[entityID];
entityElement.setAttribute('data-quickedit-entity-instance-id', entityInstanceID);
}
/**
* Fetch the field's metadata; queue or initialize it (if EntityModel exists).
*
* @param {HTMLElement} fieldElement
* A Drupal Field API field's DOM element with a data-quickedit-field-id
* attribute.
*/
function processField(fieldElement) {
var metadata = Drupal.quickedit.metadata;
var fieldID = fieldElement.getAttribute('data-quickedit-field-id');
var entityID = extractEntityID(fieldID);
// Figure out the instance ID by looking at the ancestor
// [data-quickedit-entity-id] element's data-quickedit-entity-instance-id
// attribute.
var entityElementSelector = '[data-quickedit-entity-id="' + entityID + '"]';
var entityElement = $(fieldElement).closest(entityElementSelector);
// In the case of a full entity view page, the entity title is rendered
// outside of "the entity DOM node": it's rendered as the page title. So in
// this case, we find the lowest common parent element (deepest in the tree)
// and consider that the entity element.
if (entityElement.length === 0) {
var $lowestCommonParent = $(entityElementSelector).parents().has(fieldElement).first();
entityElement = $lowestCommonParent.find(entityElementSelector);
}
var entityInstanceID = entityElement
.get(0)
.getAttribute('data-quickedit-entity-instance-id');
// Early-return if metadata for this field is missing.
if (!metadata.has(fieldID)) {
fieldsMetadataQueue.push({
el: fieldElement,
fieldID: fieldID,
entityID: entityID,
entityInstanceID: entityInstanceID
});
return;
}
// Early-return if the user is not allowed to in-place edit this field.
if (metadata.get(fieldID, 'access') !== true) {
return;
}
// If an EntityModel for this field already exists (and hence also a "Quick
// edit" contextual link), then initialize it immediately.
if (Drupal.quickedit.collections.entities.findWhere({entityID: entityID, entityInstanceID: entityInstanceID})) {
initializeField(fieldElement, fieldID, entityID, entityInstanceID);
}
// Otherwise: queue the field. It is now available to be set up when its
// corresponding entity becomes in-place editable.
else {
fieldsAvailableQueue.push({el: fieldElement, fieldID: fieldID, entityID: entityID, entityInstanceID: entityInstanceID});
}
}
/**
* Initialize a field; create FieldModel.
*
* @param {HTMLElement} fieldElement
* The field's DOM element.
* @param {string} fieldID
* The field's ID.
* @param {string} entityID
* The field's entity's ID.
* @param {string} entityInstanceID
* The field's entity's instance ID.
*/
function initializeField(fieldElement, fieldID, entityID, entityInstanceID) {
var entity = Drupal.quickedit.collections.entities.findWhere({
entityID: entityID,
entityInstanceID: entityInstanceID
});
$(fieldElement).addClass('quickedit-field');
// The FieldModel stores the state of an in-place editable entity field.
var field = new Drupal.quickedit.FieldModel({
el: fieldElement,
fieldID: fieldID,
id: fieldID + '[' + entity.get('entityInstanceID') + ']',
entity: entity,
metadata: Drupal.quickedit.metadata.get(fieldID),
acceptStateChange: _.bind(Drupal.quickedit.app.acceptEditorStateChange, Drupal.quickedit.app)
});
// Track all fields on the page.
Drupal.quickedit.collections.fields.add(field);
}
/**
* Fetches metadata for fields whose metadata is missing.
*
* Fields whose metadata is missing are tracked at fieldsMetadataQueue.
*
* @param {function} callback
* A callback function that receives field elements whose metadata will just
* have been fetched.
*/
function fetchMissingMetadata(callback) {
if (fieldsMetadataQueue.length) {
var fieldIDs = _.pluck(fieldsMetadataQueue, 'fieldID');
var fieldElementsWithoutMetadata = _.pluck(fieldsMetadataQueue, 'el');
var entityIDs = _.uniq(_.pluck(fieldsMetadataQueue, 'entityID'), true);
// Ensure we only request entityIDs for which we don't have metadata yet.
entityIDs = _.difference(entityIDs, Drupal.quickedit.metadata.intersection(entityIDs));
fieldsMetadataQueue = [];
$.ajax({
url: Drupal.url('quickedit/metadata'),
type: 'POST',
data: {
'fields[]': fieldIDs,
'entities[]': entityIDs
},
dataType: 'json',
success: function (results) {
// Store the metadata.
_.each(results, function (fieldMetadata, fieldID) {
Drupal.quickedit.metadata.add(fieldID, fieldMetadata);
});
callback(fieldElementsWithoutMetadata);
}
});
}
}
/**
* Loads missing in-place editor's attachments (JavaScript and CSS files).
*
* Missing in-place editors are those whose fields are actively being used on
* the page but don't have.
*
* @param {function} callback
* Callback function to be called when the missing in-place editors (if any)
* have been inserted into the DOM. i.e. they may still be loading.
*/
function loadMissingEditors(callback) {
var loadedEditors = _.keys(Drupal.quickedit.editors);
var missingEditors = [];
Drupal.quickedit.collections.fields.each(function (fieldModel) {
var metadata = Drupal.quickedit.metadata.get(fieldModel.get('fieldID'));
if (metadata.access && _.indexOf(loadedEditors, metadata.editor) === -1) {
missingEditors.push(metadata.editor);
// Set a stub, to prevent subsequent calls to loadMissingEditors() from
// loading the same in-place editor again. Loading an in-place editor
// requires talking to a server, to download its JavaScript, then
// executing its JavaScript, and only then its Drupal.quickedit.editors
// entry will be set.
Drupal.quickedit.editors[metadata.editor] = false;
}
});
missingEditors = _.uniq(missingEditors);
if (missingEditors.length === 0) {
callback();
return;
}
// @see https://www.drupal.org/node/2029999.
// Create a Drupal.Ajax instance to load the form.
var loadEditorsAjax = Drupal.ajax({
url: Drupal.url('quickedit/attachments'),
submit: {'editors[]': missingEditors}
});
// Implement a scoped insert AJAX command: calls the callback after all AJAX
// command functions have been executed (hence the deferred calling).
var realInsert = Drupal.AjaxCommands.prototype.insert;
loadEditorsAjax.commands.insert = function (ajax, response, status) {
_.defer(callback);
realInsert(ajax, response, status);
};
// Trigger the AJAX request, which will should return AJAX commands to
// insert any missing attachments.
loadEditorsAjax.execute();
}
/**
* Attempts to set up a "Quick edit" link and corresponding EntityModel.
*
* @param {object} contextualLink
* An object with the following properties:
* - String entityID: a Quick Edit entity identifier, e.g. "node/1" or
* "block_content/5".
* - String entityInstanceID: a Quick Edit entity instance identifier,
* e.g. 0, 1 or n (depending on whether it's the first, second, or n+1st
* instance of this entity).
* - DOM el: element pointing to the contextual links placeholder for this
* entity.
* - DOM region: element pointing to the contextual region of this entity.
*
* @return {bool}
* Returns true when a contextual the given contextual link metadata can be
* removed from the queue (either because the contextual link has been set
* up or because it is certain that in-place editing is not allowed for any
* of its fields). Returns false otherwise.
*/
function initializeEntityContextualLink(contextualLink) {
var metadata = Drupal.quickedit.metadata;
// Check if the user has permission to edit at least one of them.
function hasFieldWithPermission(fieldIDs) {
for (var i = 0; i < fieldIDs.length; i++) {
var fieldID = fieldIDs[i];
if (metadata.get(fieldID, 'access') === true) {
return true;
}
}
return false;
}
// Checks if the metadata for all given field IDs exists.
function allMetadataExists(fieldIDs) {
return fieldIDs.length === metadata.intersection(fieldIDs).length;
}
// Find all fields for this entity instance and collect their field IDs.
var fields = _.where(fieldsAvailableQueue, {
entityID: contextualLink.entityID,
entityInstanceID: contextualLink.entityInstanceID
});
var fieldIDs = _.pluck(fields, 'fieldID');
// No fields found yet.
if (fieldIDs.length === 0) {
return false;
}
// The entity for the given contextual link contains at least one field that
// the current user may edit in-place; instantiate EntityModel,
// EntityDecorationView and ContextualLinkView.
else if (hasFieldWithPermission(fieldIDs)) {
var entityModel = new Drupal.quickedit.EntityModel({
el: contextualLink.region,
entityID: contextualLink.entityID,
entityInstanceID: contextualLink.entityInstanceID,
id: contextualLink.entityID + '[' + contextualLink.entityInstanceID + ']',
label: Drupal.quickedit.metadata.get(contextualLink.entityID, 'label')
});
Drupal.quickedit.collections.entities.add(entityModel);
// Create an EntityDecorationView associated with the root DOM node of the
// entity.
var entityDecorationView = new Drupal.quickedit.EntityDecorationView({
el: contextualLink.region,
model: entityModel
});
entityModel.set('entityDecorationView', entityDecorationView);
// Initialize all queued fields within this entity (creates FieldModels).
_.each(fields, function (field) {
initializeField(field.el, field.fieldID, contextualLink.entityID, contextualLink.entityInstanceID);
});
fieldsAvailableQueue = _.difference(fieldsAvailableQueue, fields);
// Initialization should only be called once. Use Underscore's once method
// to get a one-time use version of the function.
var initContextualLink = _.once(function () {
var $links = $(contextualLink.el).find('.contextual-links');
var contextualLinkView = new Drupal.quickedit.ContextualLinkView($.extend({
el: $('<li class="quickedit"><a href="" role="button" aria-pressed="false"></a></li>').prependTo($links),
model: entityModel,
appModel: Drupal.quickedit.app.model
}, options));
entityModel.set('contextualLinkView', contextualLinkView);
});
// Set up ContextualLinkView after loading any missing in-place editors.
loadMissingEditors(initContextualLink);
return true;
}
// There was not at least one field that the current user may edit in-place,
// even though the metadata for all fields within this entity is available.
else if (allMetadataExists(fieldIDs)) {
return true;
}
return false;
}
/**
* Delete models and queue items that are contained within a given context.
*
* Deletes any contained EntityModels (plus their associated FieldModels and
* ContextualLinkView) and FieldModels, as well as the corresponding queues.
*
* After EntityModels, FieldModels must also be deleted, because it is
* possible in Drupal for a field DOM element to exist outside of the entity
* DOM element, e.g. when viewing the full node, the title of the node is not
* rendered within the node (the entity) but as the page title.
*
* Note: this will not delete an entity that is actively being in-place
* edited.
*
* @param {jQuery} $context
* The context within which to delete.
*/
function deleteContainedModelsAndQueues($context) {
$context.find('[data-quickedit-entity-id]').addBack('[data-quickedit-entity-id]').each(function (index, entityElement) {
// Delete entity model.
var entityModel = Drupal.quickedit.collections.entities.findWhere({el: entityElement});
if (entityModel) {
var contextualLinkView = entityModel.get('contextualLinkView');
contextualLinkView.undelegateEvents();
contextualLinkView.remove();
// Remove the EntityDecorationView.
entityModel.get('entityDecorationView').remove();
// Destroy the EntityModel; this will also destroy its FieldModels.
entityModel.destroy();
}
// Filter queue.
function hasOtherRegion(contextualLink) {
return contextualLink.region !== entityElement;
}
contextualLinksQueue = _.filter(contextualLinksQueue, hasOtherRegion);
});
$context.find('[data-quickedit-field-id]').addBack('[data-quickedit-field-id]').each(function (index, fieldElement) {
// Delete field models.
Drupal.quickedit.collections.fields.chain()
.filter(function (fieldModel) { return fieldModel.get('el') === fieldElement; })
.invoke('destroy');
// Filter queues.
function hasOtherFieldElement(field) {
return field.el !== fieldElement;
}
fieldsMetadataQueue = _.filter(fieldsMetadataQueue, hasOtherFieldElement);
fieldsAvailableQueue = _.filter(fieldsAvailableQueue, hasOtherFieldElement);
});
}
})(jQuery, _, Backbone, Drupal, drupalSettings, window.JSON, window.sessionStorage);
;
/**
* @file
* Provides utility functions for Quick Edit.
*/
(function ($, Drupal) {
'use strict';
/**
* @namespace
*/
Drupal.quickedit.util = Drupal.quickedit.util || {};
/**
* @namespace
*/
Drupal.quickedit.util.constants = {};
/**
*
* @type {string}
*/
Drupal.quickedit.util.constants.transitionEnd = 'transitionEnd.quickedit webkitTransitionEnd.quickedit transitionend.quickedit msTransitionEnd.quickedit oTransitionEnd.quickedit';
/**
* Converts a field id into a formatted url path.
*
* @example
* Drupal.quickedit.util.buildUrl(
* 'node/1/body/und/full',
* '/quickedit/form/!entity_type/!id/!field_name/!langcode/!view_mode'
* );
*
* @param {string} id
* The id of an editable field.
* @param {string} urlFormat
* The Controller route for field processing.
*
* @return {string}
* The formatted URL.
*/
Drupal.quickedit.util.buildUrl = function (id, urlFormat) {
var parts = id.split('/');
return Drupal.formatString(decodeURIComponent(urlFormat), {
'!entity_type': parts[0],
'!id': parts[1],
'!field_name': parts[2],
'!langcode': parts[3],
'!view_mode': parts[4]
});
};
/**
* Shows a network error modal dialog.
*
* @param {string} title
* The title to use in the modal dialog.
* @param {string} message
* The message to use in the modal dialog.
*/
Drupal.quickedit.util.networkErrorModal = function (title, message) {
var $message = $('<div>' + message + '</div>');
var networkErrorModal = Drupal.dialog($message.get(0), {
title: title,
dialogClass: 'quickedit-network-error',
buttons: [
{
text: Drupal.t('OK'),
click: function () {
networkErrorModal.close();
},
primary: true
}
],
create: function () {
$(this).parent().find('.ui-dialog-titlebar-close').remove();
},
close: function (event) {
// Automatically destroy the DOM element that was used for the dialog.
$(event.target).remove();
}
});
networkErrorModal.showModal();
};
/**
* @namespace
*/
Drupal.quickedit.util.form = {
/**
* Loads a form, calls a callback to insert.
*
* Leverages {@link Drupal.Ajax}' ability to have scoped (per-instance)
* command implementations to be able to call a callback.
*
* @param {object} options
* An object with the following keys:
* @param {string} options.fieldID
* The field ID that uniquely identifies the field for which this form
* will be loaded.
* @param {bool} options.nocssjs
* Boolean indicating whether no CSS and JS should be returned (necessary
* when the form is invisible to the user).
* @param {bool} options.reset
* Boolean indicating whether the data stored for this field's entity in
* PrivateTempStore should be used or reset.
* @param {function} callback
* A callback function that will receive the form to be inserted, as well
* as the ajax object, necessary if the callback wants to perform other
* Ajax commands.
*/
load: function (options, callback) {
var fieldID = options.fieldID;
// Create a Drupal.ajax instance to load the form.
var formLoaderAjax = Drupal.ajax({
url: Drupal.quickedit.util.buildUrl(fieldID, Drupal.url('quickedit/form/!entity_type/!id/!field_name/!langcode/!view_mode')),
submit: {
nocssjs: options.nocssjs,
reset: options.reset
},
error: function (xhr, url) {
// Show a modal to inform the user of the network error.
var fieldLabel = Drupal.quickedit.metadata.get(fieldID, 'label');
var message = Drupal.t('Could not load the form for <q>@field-label</q>, either due to a website problem or a network connection problem.<br>Please try again.', {'@field-label': fieldLabel});
Drupal.quickedit.util.networkErrorModal(Drupal.t('Network problem!'), message);
// Change the state back to "candidate", to allow the user to start
// in-place editing of the field again.
var fieldModel = Drupal.quickedit.app.model.get('activeField');
fieldModel.set('state', 'candidate');
}
});
// Implement a scoped quickeditFieldForm AJAX command: calls the callback.
formLoaderAjax.commands.quickeditFieldForm = function (ajax, response, status) {
callback(response.data, ajax);
Drupal.ajax.instances[this.instanceIndex] = null;
};
// This will ensure our scoped quickeditFieldForm AJAX command gets
// called.
formLoaderAjax.execute();
},
/**
* Creates a {@link Drupal.Ajax} instance that is used to save a form.
*
* @param {object} options
* Submit options to the form.
* @param {bool} options.nocssjs
* Boolean indicating whether no CSS and JS should be returned (necessary
* when the form is invisible to the user).
* @param {Array.<string>} options.other_view_modes
* Array containing view mode IDs (of other instances of this field on the
* page).
* @param {jQuery} $submit
* The submit element.
*
* @return {Drupal.Ajax}
* A {@link Drupal.Ajax} instance.
*/
ajaxifySaving: function (options, $submit) {
// Re-wire the form to handle submit.
var settings = {
url: $submit.closest('form').attr('action'),
setClick: true,
event: 'click.quickedit',
progress: false,
submit: {
nocssjs: options.nocssjs,
other_view_modes: options.other_view_modes
},
/**
* Reimplement the success handler.
*
* Ensure {@link Drupal.attachBehaviors} does not get called on the
* form.
*
* @param {Drupal.AjaxCommands~commandDefinition} response
* The Drupal AJAX response.
* @param {number} [status]
* The HTTP status code.
*/
success: function (response, status) {
for (var i in response) {
if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
this.commands[response[i].command](this, response[i], status);
}
}
},
base: $submit.attr('id'),
element: $submit[0]
};
return Drupal.ajax(settings);
},
/**
* Cleans up the {@link Drupal.Ajax} instance that is used to save the form.
*
* @param {Drupal.Ajax} ajax
* A {@link Drupal.Ajax} instance that was returned by
* {@link Drupal.quickedit.form.ajaxifySaving}.
*/
unajaxifySaving: function (ajax) {
$(ajax.element).off('click.quickedit');
}
};
})(jQuery, Drupal);
;
/**
* @file
* A Backbone Model subclass that enforces validation when calling set().
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.quickedit.BaseModel = Backbone.Model.extend(/** @lends Drupal.quickedit.BaseModel# */{
/**
* @constructs
*
* @augments Backbone.Model
*
* @param {object} options
* Options for the base model-
*
* @return {Drupal.quickedit.BaseModel}
* A quickedit base model.
*/
initialize: function (options) {
this.__initialized = true;
return Backbone.Model.prototype.initialize.call(this, options);
},
/**
* Set a value on the model
*
* @param {object|string} key
* The key to set a value for.
* @param {*} val
* The value to set.
* @param {object} [options]
* Options for the model.
*
* @return {*}
* The result of `Backbone.Model.prototype.set` with the specified
* parameters.
*/
set: function (key, val, options) {
if (this.__initialized) {
// Deal with both the "key", value and {key:value}-style arguments.
if (typeof key === 'object') {
key.validate = true;
}
else {
if (!options) {
options = {};
}
options.validate = true;
}
}
return Backbone.Model.prototype.set.call(this, key, val, options);
}
});
}(Drupal, Backbone));
;
/**
* @file
* A Backbone Model for the state of the in-place editing application.
*
* @see Drupal.quickedit.AppView
*/
(function (Backbone, Drupal) {
'use strict';
/**
* @constructor
*
* @augments Backbone.Model
*/
Drupal.quickedit.AppModel = Backbone.Model.extend(/** @lends Drupal.quickedit.AppModel# */{
/**
* @type {object}
*
* @prop {Drupal.quickedit.FieldModel} highlightedField
* @prop {Drupal.quickedit.FieldModel} activeField
* @prop {Drupal.dialog~dialogDefinition} activeModal
*/
defaults: /** @lends Drupal.quickedit.AppModel# */{
/**
* The currently state='highlighted' Drupal.quickedit.FieldModel, if any.
*
* @type {Drupal.quickedit.FieldModel}
*
* @see Drupal.quickedit.FieldModel.states
*/
highlightedField: null,
/**
* The currently state = 'active' Drupal.quickedit.FieldModel, if any.
*
* @type {Drupal.quickedit.FieldModel}
*
* @see Drupal.quickedit.FieldModel.states
*/
activeField: null,
/**
* Reference to a {@link Drupal.dialog} instance if a state change
* requires confirmation.
*
* @type {Drupal.dialog~dialogDefinition}
*/
activeModal: null
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the state of an in-place editable entity in the DOM.
*/
(function (_, $, Backbone, Drupal) {
'use strict';
Drupal.quickedit.EntityModel = Drupal.quickedit.BaseModel.extend(/** @lends Drupal.quickedit.EntityModel# */{
/**
* @type {object}
*/
defaults: /** @lends Drupal.quickedit.EntityModel# */{
/**
* The DOM element that represents this entity.
*
* It may seem bizarre to have a DOM element in a Backbone Model, but we
* need to be able to map entities in the DOM to EntityModels in memory.
*
* @type {HTMLElement}
*/
el: null,
/**
* An entity ID, of the form `<entity type>/<entity ID>`
*
* @example
* "node/1"
*
* @type {string}
*/
entityID: null,
/**
* An entity instance ID.
*
* The first instance of a specific entity (i.e. with a given entity ID)
* is assigned 0, the second 1, and so on.
*
* @type {number}
*/
entityInstanceID: null,
/**
* The unique ID of this entity instance on the page, of the form
* `<entity type>/<entity ID>[entity instance ID]`
*
* @example
* "node/1[0]"
*
* @type {string}
*/
id: null,
/**
* The label of the entity.
*
* @type {string}
*/
label: null,
/**
* A FieldCollection for all fields of the entity.
*
* @type {Drupal.quickedit.FieldCollection}
*
* @see Drupal.quickedit.FieldCollection
*/
fields: null,
// The attributes below are stateful. The ones above will never change
// during the life of a EntityModel instance.
/**
* Indicates whether this entity is currently being edited in-place.
*
* @type {bool}
*/
isActive: false,
/**
* Whether one or more fields are already been stored in PrivateTempStore.
*
* @type {bool}
*/
inTempStore: false,
/**
* Indicates whether a "Save" button is necessary or not.
*
* Whether one or more fields have already been stored in PrivateTempStore
* *or* the field that's currently being edited is in the 'changed' or a
* later state.
*
* @type {bool}
*/
isDirty: false,
/**
* Whether the request to the server has been made to commit this entity.
*
* Used to prevent multiple such requests.
*
* @type {bool}
*/
isCommitting: false,
/**
* The current processing state of an entity.
*
* @type {string}
*/
state: 'closed',
/**
* IDs of fields whose new values have been stored in PrivateTempStore.
*
* We must store this on the EntityModel as well (even though it already
* is on the FieldModel) because when a field is rerendered, its
* FieldModel is destroyed and this allows us to transition it back to
* the proper state.
*
* @type {Array.<string>}
*/
fieldsInTempStore: [],
/**
* A flag the tells the application that this EntityModel must be reloaded
* in order to restore the original values to its fields in the client.
*
* @type {bool}
*/
reload: false
},
/**
* @constructs
*
* @augments Drupal.quickedit.BaseModel
*/
initialize: function () {
this.set('fields', new Drupal.quickedit.FieldCollection());
// Respond to entity state changes.
this.listenTo(this, 'change:state', this.stateChange);
// The state of the entity is largely dependent on the state of its
// fields.
this.listenTo(this.get('fields'), 'change:state', this.fieldStateChange);
// Call Drupal.quickedit.BaseModel's initialize() method.
Drupal.quickedit.BaseModel.prototype.initialize.call(this);
},
/**
* Updates FieldModels' states when an EntityModel change occurs.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* The entity model
* @param {string} state
* The state of the associated entity. One of
* {@link Drupal.quickedit.EntityModel.states}.
* @param {object} options
* Options for the entity model.
*/
stateChange: function (entityModel, state, options) {
var to = state;
switch (to) {
case 'closed':
this.set({
isActive: false,
inTempStore: false,
isDirty: false
});
break;
case 'launching':
break;
case 'opening':
// Set the fields to candidate state.
entityModel.get('fields').each(function (fieldModel) {
fieldModel.set('state', 'candidate', options);
});
break;
case 'opened':
// The entity is now ready for editing!
this.set('isActive', true);
break;
case 'committing':
// The user indicated they want to save the entity.
var fields = this.get('fields');
// For fields that are in an active state, transition them to
// candidate.
fields.chain()
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['active']).length;
})
.each(function (fieldModel) {
fieldModel.set('state', 'candidate');
});
// For fields that are in a changed state, field values must first be
// stored in PrivateTempStore.
fields.chain()
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], Drupal.quickedit.app.changedFieldStates).length;
})
.each(function (fieldModel) {
fieldModel.set('state', 'saving');
});
break;
case 'deactivating':
var changedFields = this.get('fields')
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['changed', 'invalid']).length;
});
// If the entity contains unconfirmed or unsaved changes, return the
// entity to an opened state and ask the user if they would like to
// save the changes or discard the changes.
// 1. One of the fields is in a changed state. The changed field
// might just be a change in the client or it might have been saved
// to tempstore.
// 2. The saved flag is empty and the confirmed flag is empty. If
// the entity has been saved to the server, the fields changed in
// the client are irrelevant. If the changes are confirmed, then
// proceed to set the fields to candidate state.
if ((changedFields.length || this.get('fieldsInTempStore').length) && (!options.saved && !options.confirmed)) {
// Cancel deactivation until the user confirms save or discard.
this.set('state', 'opened', {confirming: true});
// An action in reaction to state change must be deferred.
_.defer(function () {
Drupal.quickedit.app.confirmEntityDeactivation(entityModel);
});
}
else {
var invalidFields = this.get('fields')
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['invalid']).length;
});
// Indicate if this EntityModel needs to be reloaded in order to
// restore the original values of its fields.
entityModel.set('reload', (this.get('fieldsInTempStore').length || invalidFields.length));
// Set all fields to the 'candidate' state. A changed field may have
// to go through confirmation first.
entityModel.get('fields').each(function (fieldModel) {
// If the field is already in the candidate state, trigger a
// change event so that the entityModel can move to the next state
// in deactivation.
if (_.intersection([fieldModel.get('state')], ['candidate', 'highlighted']).length) {
fieldModel.trigger('change:state', fieldModel, fieldModel.get('state'), options);
}
else {
fieldModel.set('state', 'candidate', options);
}
});
}
break;
case 'closing':
// Set all fields to the 'inactive' state.
options.reason = 'stop';
this.get('fields').each(function (fieldModel) {
fieldModel.set({
inTempStore: false,
state: 'inactive'
}, options);
});
break;
}
},
/**
* Updates a Field and Entity model's "inTempStore" when appropriate.
*
* Helper function.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* The model of the entity for which a field's state attribute has
* changed.
* @param {Drupal.quickedit.FieldModel} fieldModel
* The model of the field whose state attribute has changed.
*
* @see Drupal.quickedit.EntityModel#fieldStateChange
*/
_updateInTempStoreAttributes: function (entityModel, fieldModel) {
var current = fieldModel.get('state');
var previous = fieldModel.previous('state');
var fieldsInTempStore = entityModel.get('fieldsInTempStore');
// If the fieldModel changed to the 'saved' state: remember that this
// field was saved to PrivateTempStore.
if (current === 'saved') {
// Mark the entity as saved in PrivateTempStore, so that we can pass the
// proper "reset PrivateTempStore" boolean value when communicating with
// the server.
entityModel.set('inTempStore', true);
// Mark the field as saved in PrivateTempStore, so that visual
// indicators signifying just that may be rendered.
fieldModel.set('inTempStore', true);
// Remember that this field is in PrivateTempStore, restore when
// rerendered.
fieldsInTempStore.push(fieldModel.get('fieldID'));
fieldsInTempStore = _.uniq(fieldsInTempStore);
entityModel.set('fieldsInTempStore', fieldsInTempStore);
}
// If the fieldModel changed to the 'candidate' state from the
// 'inactive' state, then this is a field for this entity that got
// rerendered. Restore its previous 'inTempStore' attribute value.
else if (current === 'candidate' && previous === 'inactive') {
fieldModel.set('inTempStore', _.intersection([fieldModel.get('fieldID')], fieldsInTempStore).length > 0);
}
},
/**
* Reacts to state changes in this entity's fields.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The model of the field whose state attribute changed.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
fieldStateChange: function (fieldModel, state) {
var entityModel = this;
var fieldState = state;
// Switch on the entityModel state.
// The EntityModel responds to FieldModel state changes as a function of
// its state. For example, a field switching back to 'candidate' state
// when its entity is in the 'opened' state has no effect on the entity.
// But that same switch back to 'candidate' state of a field when the
// entity is in the 'committing' state might allow the entity to proceed
// with the commit flow.
switch (this.get('state')) {
case 'closed':
case 'launching':
// It should be impossible to reach these: fields can't change state
// while the entity is closed or still launching.
break;
case 'opening':
// We must change the entity to the 'opened' state, but it must first
// be confirmed that all of its fieldModels have transitioned to the
// 'candidate' state.
// We do this here, because this is called every time a fieldModel
// changes state, hence each time this is called, we get closer to the
// goal of having all fieldModels in the 'candidate' state.
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'opened', {
'accept-field-states': Drupal.quickedit.app.readyFieldStates
});
});
break;
case 'opened':
// Set the isDirty attribute when appropriate so that it is known when
// to display the "Save" button in the entity toolbar.
// Note that once a field has been changed, there's no way to discard
// that change, hence it will have to be saved into PrivateTempStore,
// or the in-place editing of this field will have to be stopped
// completely. In other words: once any field enters the 'changed'
// field, then for the remainder of the in-place editing session, the
// entity is by definition dirty.
if (fieldState === 'changed') {
entityModel.set('isDirty', true);
}
else {
this._updateInTempStoreAttributes(entityModel, fieldModel);
}
break;
case 'committing':
// If the field save returned a validation error, set the state of the
// entity back to 'opened'.
if (fieldState === 'invalid') {
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'opened', {reason: 'invalid'});
});
}
else {
this._updateInTempStoreAttributes(entityModel, fieldModel);
}
// Attempt to save the entity. If the entity's fields are not yet all
// in a ready state, the save will not be processed.
var options = {
'accept-field-states': Drupal.quickedit.app.readyFieldStates
};
if (entityModel.set('isCommitting', true, options)) {
entityModel.save({
success: function () {
entityModel.set({
state: 'deactivating',
isCommitting: false
}, {saved: true});
},
error: function () {
// Reset the "isCommitting" mutex.
entityModel.set('isCommitting', false);
// Change the state back to "opened", to allow the user to hit
// the "Save" button again.
entityModel.set('state', 'opened', {reason: 'networkerror'});
// Show a modal to inform the user of the network error.
var message = Drupal.t('Your changes to <q>@entity-title</q> could not be saved, either due to a website problem or a network connection problem.<br>Please try again.', {'@entity-title': entityModel.get('label')});
Drupal.quickedit.util.networkErrorModal(Drupal.t('Network problem!'), message);
}
});
}
break;
case 'deactivating':
// When setting the entity to 'closing', require that all fieldModels
// are in either the 'candidate' or 'highlighted' state.
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'closing', {
'accept-field-states': Drupal.quickedit.app.readyFieldStates
});
});
break;
case 'closing':
// When setting the entity to 'closed', require that all fieldModels
// are in the 'inactive' state.
// A state change in reaction to another state change must be
// deferred.
_.defer(function () {
entityModel.set('state', 'closed', {
'accept-field-states': ['inactive']
});
});
break;
}
},
/**
* Fires an AJAX request to the REST save URL for an entity.
*
* @param {object} options
* An object of options that contains:
* @param {function} [options.success]
* A function to invoke if the entity is successfully saved.
*/
save: function (options) {
var entityModel = this;
// Create a Drupal.ajax instance to save the entity.
var entitySaverAjax = Drupal.ajax({
url: Drupal.url('quickedit/entity/' + entityModel.get('entityID')),
error: function () {
// Let the Drupal.quickedit.EntityModel Backbone model's error()
// method handle errors.
options.error.call(entityModel);
}
});
// Entity saved successfully.
entitySaverAjax.commands.quickeditEntitySaved = function (ajax, response, status) {
// All fields have been moved from PrivateTempStore to permanent
// storage, update the "inTempStore" attribute on FieldModels, on the
// EntityModel and clear EntityModel's "fieldInTempStore" attribute.
entityModel.get('fields').each(function (fieldModel) {
fieldModel.set('inTempStore', false);
});
entityModel.set('inTempStore', false);
entityModel.set('fieldsInTempStore', []);
// Invoke the optional success callback.
if (options.success) {
options.success.call(entityModel);
}
};
// Trigger the AJAX request, which will will return the
// quickeditEntitySaved AJAX command to which we then react.
entitySaverAjax.execute();
},
/**
* Validate the entity model.
*
* @param {object} attrs
* The attributes changes in the save or set call.
* @param {object} options
* An object with the following option:
* @param {string} [options.reason]
* A string that conveys a particular reason to allow for an exceptional
* state change.
* @param {Array} options.accept-field-states
* An array of strings that represent field states that the entities must
* be in to validate. For example, if `accept-field-states` is
* `['candidate', 'highlighted']`, then all the fields of the entity must
* be in either of these two states for the save or set call to
* validate and proceed.
*
* @return {string}
* A string to say something about the state of the entity model.
*/
validate: function (attrs, options) {
var acceptedFieldStates = options['accept-field-states'] || [];
// Validate state change.
var currentState = this.get('state');
var nextState = attrs.state;
if (currentState !== nextState) {
// Ensure it's a valid state.
if (_.indexOf(this.constructor.states, nextState) === -1) {
return '"' + nextState + '" is an invalid state';
}
// Ensure it's a state change that is allowed.
// Check if the acceptStateChange function accepts it.
if (!this._acceptStateChange(currentState, nextState, options)) {
return 'state change not accepted';
}
// If that function accepts it, then ensure all fields are also in an
// acceptable state.
else if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) {
return 'state change not accepted because fields are not in acceptable state';
}
}
// Validate setting isCommitting = true.
var currentIsCommitting = this.get('isCommitting');
var nextIsCommitting = attrs.isCommitting;
if (currentIsCommitting === false && nextIsCommitting === true) {
if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) {
return 'isCommitting change not accepted because fields are not in acceptable state';
}
}
else if (currentIsCommitting === true && nextIsCommitting === true) {
return 'isCommitting is a mutex, hence only changes are allowed';
}
},
/**
* Checks if a state change can be accepted.
*
* @param {string} from
* From state.
* @param {string} to
* To state.
* @param {object} context
* Context for the check.
* @param {string} context.reason
* The reason for the state change.
* @param {bool} context.confirming
* Whether context is confirming or not.
*
* @return {bool}
* Whether the state change is accepted or not.
*
* @see Drupal.quickedit.AppView#acceptEditorStateChange
*/
_acceptStateChange: function (from, to, context) {
var accept = true;
// In general, enforce the states sequence. Disallow going back from a
// "later" state to an "earlier" state, except in explicitly allowed
// cases.
if (!this.constructor.followsStateSequence(from, to)) {
accept = false;
// Allow: closing -> closed.
// Necessary to stop editing an entity.
if (from === 'closing' && to === 'closed') {
accept = true;
}
// Allow: committing -> opened.
// Necessary to be able to correct an invalid field, or to hit the
// "Save" button again after a server/network error.
else if (from === 'committing' && to === 'opened' && context.reason && (context.reason === 'invalid' || context.reason === 'networkerror')) {
accept = true;
}
// Allow: deactivating -> opened.
// Necessary to be able to confirm changes with the user.
else if (from === 'deactivating' && to === 'opened' && context.confirming) {
accept = true;
}
// Allow: opened -> deactivating.
// Necessary to be able to stop editing.
else if (from === 'opened' && to === 'deactivating' && context.confirmed) {
accept = true;
}
}
return accept;
},
/**
* Checks if fields have acceptable states.
*
* @param {Array} acceptedFieldStates
* An array of acceptable field states to check for.
*
* @return {bool}
* Whether the fields have an acceptable state.
*
* @see Drupal.quickedit.EntityModel#validate
*/
_fieldsHaveAcceptableStates: function (acceptedFieldStates) {
var accept = true;
// If no acceptable field states are provided, assume all field states are
// acceptable. We want to let validation pass as a default and only
// check validity on calls to set that explicitly request it.
if (acceptedFieldStates.length > 0) {
var fieldStates = this.get('fields').pluck('state') || [];
// If not all fields are in one of the accepted field states, then we
// still can't allow this state change.
if (_.difference(fieldStates, acceptedFieldStates).length) {
accept = false;
}
}
return accept;
},
/**
* Destroys the entity model.
*
* @param {object} options
* Options for the entity model.
*/
destroy: function (options) {
Drupal.quickedit.BaseModel.prototype.destroy.call(this, options);
this.stopListening();
// Destroy all fields of this entity.
this.get('fields').reset();
},
/**
* @inheritdoc
*/
sync: function () {
// We don't use REST updates to sync.
return;
}
}, /** @lends Drupal.quickedit.EntityModel */{
/**
* Sequence of all possible states an entity can be in during quickediting.
*
* @type {Array.<string>}
*/
states: [
// Initial state, like field's 'inactive' OR the user has just finished
// in-place editing this entity.
// - Trigger: none (initial) or EntityModel (finished).
// - Expected behavior: (when not initial state): tear down
// EntityToolbarView, in-place editors and related views.
'closed',
// User has activated in-place editing of this entity.
// - Trigger: user.
// - Expected behavior: the EntityToolbarView is gets set up, in-place
// editors (EditorViews) and related views for this entity's fields are
// set up. Upon completion of those, the state is changed to 'opening'.
'launching',
// Launching has finished.
// - Trigger: application.
// - Guarantees: in-place editors ready for use, all entity and field
// views have been set up, all fields are in the 'inactive' state.
// - Expected behavior: all fields are changed to the 'candidate' state
// and once this is completed, the entity state will be changed to
// 'opened'.
'opening',
// Opening has finished.
// - Trigger: EntityModel.
// - Guarantees: see 'opening', all fields are in the 'candidate' state.
// - Expected behavior: the user is able to actually use in-place editing.
'opened',
// User has clicked the 'Save' button (and has thus changed at least one
// field).
// - Trigger: user.
// - Guarantees: see 'opened', plus: either a changed field is in
// PrivateTempStore, or the user has just modified a field without
// activating (switching to) another field.
// - Expected behavior: 1) if any of the fields are not yet in
// PrivateTempStore, save them to PrivateTempStore, 2) if then any of
// the fields has the 'invalid' state, then change the entity state back
// to 'opened', otherwise: save the entity by committing it from
// PrivateTempStore into permanent storage.
'committing',
// User has clicked the 'Close' button, or has clicked the 'Save' button
// and that was successfully completed.
// - Trigger: user or EntityModel.
// - Guarantees: when having clicked 'Close' hardly any: fields may be in
// a variety of states; when having clicked 'Save': all fields are in
// the 'candidate' state.
// - Expected behavior: transition all fields to the 'candidate' state,
// possibly requiring confirmation in the case of having clicked
// 'Close'.
'deactivating',
// Deactivation has been completed.
// - Trigger: EntityModel.
// - Guarantees: all fields are in the 'candidate' state.
// - Expected behavior: change all fields to the 'inactive' state.
'closing'
],
/**
* Indicates whether the 'from' state comes before the 'to' state.
*
* @param {string} from
* One of {@link Drupal.quickedit.EntityModel.states}.
* @param {string} to
* One of {@link Drupal.quickedit.EntityModel.states}.
*
* @return {bool}
* Whether the 'from' state comes before the 'to' state.
*/
followsStateSequence: function (from, to) {
return _.indexOf(this.states, from) < _.indexOf(this.states, to);
}
});
/**
* @constructor
*
* @augments Backbone.Collection
*/
Drupal.quickedit.EntityCollection = Backbone.Collection.extend(/** @lends Drupal.quickedit.EntityCollection# */{
/**
* @type {Drupal.quickedit.EntityModel}
*/
model: Drupal.quickedit.EntityModel
});
}(_, jQuery, Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the state of an in-place editable field in the DOM.
*/
(function (_, Backbone, Drupal) {
'use strict';
Drupal.quickedit.FieldModel = Drupal.quickedit.BaseModel.extend(/** @lends Drupal.quickedit.FieldModel# */{
/**
* @type {object}
*/
defaults: /** @lends Drupal.quickedit.FieldModel# */{
/**
* The DOM element that represents this field. It may seem bizarre to have
* a DOM element in a Backbone Model, but we need to be able to map fields
* in the DOM to FieldModels in memory.
*/
el: null,
/**
* A field ID, of the form
* `<entity type>/<id>/<field name>/<language>/<view mode>`
*
* @example
* "node/1/field_tags/und/full"
*/
fieldID: null,
/**
* The unique ID of this field within its entity instance on the page, of
* the form `<entity type>/<id>/<field name>/<language>/<view
* mode>[entity instance ID]`.
*
* @example
* "node/1/field_tags/und/full[0]"
*/
id: null,
/**
* A {@link Drupal.quickedit.EntityModel}. Its "fields" attribute, which
* is a FieldCollection, is automatically updated to include this
* FieldModel.
*/
entity: null,
/**
* This field's metadata as returned by the
* QuickEditController::metadata().
*/
metadata: null,
/**
* Callback function for validating changes between states. Receives the
* previous state, new state, context, and a callback.
*/
acceptStateChange: null,
/**
* A logical field ID, of the form
* `<entity type>/<id>/<field name>/<language>`, i.e. the fieldID without
* the view mode, to be able to identify other instances of the same
* field on the page but rendered in a different view mode.
*
* @example
* "node/1/field_tags/und".
*/
logicalFieldID: null,
// The attributes below are stateful. The ones above will never change
// during the life of a FieldModel instance.
/**
* In-place editing state of this field. Defaults to the initial state.
* Possible values: {@link Drupal.quickedit.FieldModel.states}.
*/
state: 'inactive',
/**
* The field is currently in the 'changed' state or one of the following
* states in which the field is still changed.
*/
isChanged: false,
/**
* Is tracked by the EntityModel, is mirrored here solely for decorative
* purposes: so that FieldDecorationView.renderChanged() can react to it.
*/
inTempStore: false,
/**
* The full HTML representation of this field (with the element that has
* the data-quickedit-field-id as the outer element). Used to propagate
* changes from this field to other instances of the same field storage.
*/
html: null,
/**
* An object containing the full HTML representations (values) of other
* view modes (keys) of this field, for other instances of this field
* displayed in a different view mode.
*/
htmlForOtherViewModes: null
},
/**
* State of an in-place editable field in the DOM.
*
* @constructs
*
* @augments Drupal.quickedit.BaseModel
*
* @param {object} options
* Options for the field model.
*/
initialize: function (options) {
// Store the original full HTML representation of this field.
this.set('html', options.el.outerHTML);
// Enlist field automatically in the associated entity's field collection.
this.get('entity').get('fields').add(this);
// Automatically generate the logical field ID.
this.set('logicalFieldID', this.get('fieldID').split('/').slice(0, 4).join('/'));
// Call Drupal.quickedit.BaseModel's initialize() method.
Drupal.quickedit.BaseModel.prototype.initialize.call(this, options);
},
/**
* Destroys the field model.
*
* @param {object} options
* Options for the field model.
*/
destroy: function (options) {
if (this.get('state') !== 'inactive') {
throw new Error('FieldModel cannot be destroyed if it is not inactive state.');
}
Drupal.quickedit.BaseModel.prototype.destroy.call(this, options);
},
/**
* @inheritdoc
*/
sync: function () {
// We don't use REST updates to sync.
return;
},
/**
* Validate function for the field model.
*
* @param {object} attrs
* The attributes changes in the save or set call.
* @param {object} options
* An object with the following option:
* @param {string} [options.reason]
* A string that conveys a particular reason to allow for an exceptional
* state change.
* @param {Array} options.accept-field-states
* An array of strings that represent field states that the entities must
* be in to validate. For example, if `accept-field-states` is
* `['candidate', 'highlighted']`, then all the fields of the entity must
* be in either of these two states for the save or set call to
* validate and proceed.
*
* @return {string}
* A string to say something about the state of the field model.
*/
validate: function (attrs, options) {
var current = this.get('state');
var next = attrs.state;
if (current !== next) {
// Ensure it's a valid state.
if (_.indexOf(this.constructor.states, next) === -1) {
return '"' + next + '" is an invalid state';
}
// Check if the acceptStateChange callback accepts it.
if (!this.get('acceptStateChange')(current, next, options, this)) {
return 'state change not accepted';
}
}
},
/**
* Extracts the entity ID from this field's ID.
*
* @return {string}
* An entity ID: a string of the format `<entity type>/<id>`.
*/
getEntityID: function () {
return this.get('fieldID').split('/').slice(0, 2).join('/');
},
/**
* Extracts the view mode ID from this field's ID.
*
* @return {string}
* A view mode ID.
*/
getViewMode: function () {
return this.get('fieldID').split('/').pop();
},
/**
* Find other instances of this field with different view modes.
*
* @return {Array}
* An array containing view mode IDs.
*/
findOtherViewModes: function () {
var currentField = this;
var otherViewModes = [];
Drupal.quickedit.collections.fields
// Find all instances of fields that display the same logical field
// (same entity, same field, just a different instance and maybe a
// different view mode).
.where({logicalFieldID: currentField.get('logicalFieldID')})
.forEach(function (field) {
// Ignore the current field.
if (field === currentField) {
return;
}
// Also ignore other fields with the same view mode.
else if (field.get('fieldID') === currentField.get('fieldID')) {
return;
}
else {
otherViewModes.push(field.getViewMode());
}
});
return otherViewModes;
}
}, /** @lends Drupal.quickedit.FieldModel */{
/**
* Sequence of all possible states a field can be in during quickediting.
*
* @type {Array.<string>}
*/
states: [
// The field associated with this FieldModel is linked to an EntityModel;
// the user can choose to start in-place editing that entity (and
// consequently this field). No in-place editor (EditorView) is associated
// with this field, because this field is not being in-place edited.
// This is both the initial (not yet in-place editing) and the end state
// (finished in-place editing).
'inactive',
// The user is in-place editing this entity, and this field is a
// candidate
// for in-place editing. In-place editor should not
// - Trigger: user.
// - Guarantees: entity is ready, in-place editor (EditorView) is
// associated with the field.
// - Expected behavior: visual indicators
// around the field indicate it is available for in-place editing, no
// in-place editor presented yet.
'candidate',
// User is highlighting this field.
// - Trigger: user.
// - Guarantees: see 'candidate'.
// - Expected behavior: visual indicators to convey highlighting, in-place
// editing toolbar shows field's label.
'highlighted',
// User has activated the in-place editing of this field; in-place editor
// is activating.
// - Trigger: user.
// - Guarantees: see 'candidate'.
// - Expected behavior: loading indicator, in-place editor is loading
// remote data (e.g. retrieve form from back-end). Upon retrieval of
// remote data, the in-place editor transitions the field's state to
// 'active'.
'activating',
// In-place editor has finished loading remote data; ready for use.
// - Trigger: in-place editor.
// - Guarantees: see 'candidate'.
// - Expected behavior: in-place editor for the field is ready for use.
'active',
// User has modified values in the in-place editor.
// - Trigger: user.
// - Guarantees: see 'candidate', plus in-place editor is ready for use.
// - Expected behavior: visual indicator of change.
'changed',
// User is saving changed field data in in-place editor to
// PrivateTempStore. The save mechanism of the in-place editor is called.
// - Trigger: user.
// - Guarantees: see 'candidate' and 'active'.
// - Expected behavior: saving indicator, in-place editor is saving field
// data into PrivateTempStore. Upon successful saving (without
// validation errors), the in-place editor transitions the field's state
// to 'saved', but to 'invalid' upon failed saving (with validation
// errors).
'saving',
// In-place editor has successfully saved the changed field.
// - Trigger: in-place editor.
// - Guarantees: see 'candidate' and 'active'.
// - Expected behavior: transition back to 'candidate' state because the
// deed is done. Then: 1) transition to 'inactive' to allow the field
// to be rerendered, 2) destroy the FieldModel (which also destroys
// attached views like the EditorView), 3) replace the existing field
// HTML with the existing HTML and 4) attach behaviors again so that the
// field becomes available again for in-place editing.
'saved',
// In-place editor has failed to saved the changed field: there were
// validation errors.
// - Trigger: in-place editor.
// - Guarantees: see 'candidate' and 'active'.
// - Expected behavior: remain in 'invalid' state, let the user make more
// changes so that he can save it again, without validation errors.
'invalid'
],
/**
* Indicates whether the 'from' state comes before the 'to' state.
*
* @param {string} from
* One of {@link Drupal.quickedit.FieldModel.states}.
* @param {string} to
* One of {@link Drupal.quickedit.FieldModel.states}.
*
* @return {bool}
* Whether the 'from' state comes before the 'to' state.
*/
followsStateSequence: function (from, to) {
return _.indexOf(this.states, from) < _.indexOf(this.states, to);
}
});
/**
* @constructor
*
* @augments Backbone.Collection
*/
Drupal.quickedit.FieldCollection = Backbone.Collection.extend(/** @lends Drupal.quickedit.FieldCollection */{
/**
* @type {Drupal.quickedit.FieldModel}
*/
model: Drupal.quickedit.FieldModel
});
}(_, Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the state of an in-place editor.
*
* @see Drupal.quickedit.EditorView
*/
(function (Backbone, Drupal) {
'use strict';
/**
* @constructor
*
* @augments Backbone.Model
*/
Drupal.quickedit.EditorModel = Backbone.Model.extend(/** @lends Drupal.quickedit.EditorModel# */{
/**
* @type {object}
*
* @prop {string} originalValue
* @prop {string} currentValue
* @prop {Array} validationErrors
*/
defaults: /** @lends Drupal.quickedit.EditorModel# */{
/**
* Not the full HTML representation of this field, but the "actual"
* original value of the field, stored by the used in-place editor, and
* in a representation that can be chosen by the in-place editor.
*
* @type {string}
*/
originalValue: null,
/**
* Analogous to originalValue, but the current value.
*
* @type {string}
*/
currentValue: null,
/**
* Stores any validation errors to be rendered.
*
* @type {Array}
*/
validationErrors: null
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone View that controls the overall "in-place editing application".
*
* @see Drupal.quickedit.AppModel
*/
(function ($, _, Backbone, Drupal) {
'use strict';
// Indicates whether the page should be reloaded after in-place editing has
// shut down. A page reload is necessary to re-instate the original HTML of
// the edited fields if in-place editing has been canceled and one or more of
// the entity's fields were saved to PrivateTempStore: one of them may have
// been changed to the empty value and hence may have been rerendered as the
// empty string, which makes it impossible for Quick Edit to know where to
// restore the original HTML.
var reload = false;
Drupal.quickedit.AppView = Backbone.View.extend(/** @lends Drupal.quickedit.AppView# */{
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.AppModel} options.model
* The application state model.
* @param {Drupal.quickedit.EntityCollection} options.entitiesCollection
* All on-page entities.
* @param {Drupal.quickedit.FieldCollection} options.fieldsCollection
* All on-page fields
*/
initialize: function (options) {
// AppView's configuration for handling states.
// @see Drupal.quickedit.FieldModel.states
this.activeFieldStates = ['activating', 'active'];
this.singleFieldStates = ['highlighted', 'activating', 'active'];
this.changedFieldStates = ['changed', 'saving', 'saved', 'invalid'];
this.readyFieldStates = ['candidate', 'highlighted'];
// Track app state.
this.listenTo(options.entitiesCollection, 'change:state', this.appStateChange);
this.listenTo(options.entitiesCollection, 'change:isActive', this.enforceSingleActiveEntity);
// Track app state.
this.listenTo(options.fieldsCollection, 'change:state', this.editorStateChange);
// Respond to field model HTML representation change events.
this.listenTo(options.fieldsCollection, 'change:html', this.renderUpdatedField);
this.listenTo(options.fieldsCollection, 'change:html', this.propagateUpdatedField);
// Respond to addition.
this.listenTo(options.fieldsCollection, 'add', this.rerenderedFieldToCandidate);
// Respond to destruction.
this.listenTo(options.fieldsCollection, 'destroy', this.teardownEditor);
},
/**
* Handles setup/teardown and state changes when the active entity changes.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* An instance of the EntityModel class.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.EntityModel.states}.
*/
appStateChange: function (entityModel, state) {
var app = this;
var entityToolbarView;
switch (state) {
case 'launching':
reload = false;
// First, create an entity toolbar view.
entityToolbarView = new Drupal.quickedit.EntityToolbarView({
model: entityModel,
appModel: this.model
});
entityModel.toolbarView = entityToolbarView;
// Second, set up in-place editors.
// They must be notified of state changes, hence this must happen
// while the associated fields are still in the 'inactive' state.
entityModel.get('fields').each(function (fieldModel) {
app.setupEditor(fieldModel);
});
// Third, transition the entity to the 'opening' state, which will
// transition all fields from 'inactive' to 'candidate'.
_.defer(function () {
entityModel.set('state', 'opening');
});
break;
case 'closed':
entityToolbarView = entityModel.toolbarView;
// First, tear down the in-place editors.
entityModel.get('fields').each(function (fieldModel) {
app.teardownEditor(fieldModel);
});
// Second, tear down the entity toolbar view.
if (entityToolbarView) {
entityToolbarView.remove();
delete entityModel.toolbarView;
}
// A page reload may be necessary to re-instate the original HTML of
// the edited fields.
if (reload) {
reload = false;
location.reload();
}
break;
}
},
/**
* Accepts or reject editor (Editor) state changes.
*
* This is what ensures that the app is in control of what happens.
*
* @param {string} from
* The previous state.
* @param {string} to
* The new state.
* @param {null|object} context
* The context that is trying to trigger the state change.
* @param {Drupal.quickedit.FieldModel} fieldModel
* The fieldModel to which this change applies.
*
* @return {bool}
* Whether the editor change was accepted or rejected.
*/
acceptEditorStateChange: function (from, to, context, fieldModel) {
var accept = true;
// If the app is in view mode, then reject all state changes except for
// those to 'inactive'.
if (context && (context.reason === 'stop' || context.reason === 'rerender')) {
if (from === 'candidate' && to === 'inactive') {
accept = true;
}
}
// Handling of edit mode state changes is more granular.
else {
// In general, enforce the states sequence. Disallow going back from a
// "later" state to an "earlier" state, except in explicitly allowed
// cases.
if (!Drupal.quickedit.FieldModel.followsStateSequence(from, to)) {
accept = false;
// Allow: activating/active -> candidate.
// Necessary to stop editing a field.
if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
accept = true;
}
// Allow: changed/invalid -> candidate.
// Necessary to stop editing a field when it is changed or invalid.
else if ((from === 'changed' || from === 'invalid') && to === 'candidate') {
accept = true;
}
// Allow: highlighted -> candidate.
// Necessary to stop highlighting a field.
else if (from === 'highlighted' && to === 'candidate') {
accept = true;
}
// Allow: saved -> candidate.
// Necessary when successfully saved a field.
else if (from === 'saved' && to === 'candidate') {
accept = true;
}
// Allow: invalid -> saving.
// Necessary to be able to save a corrected, invalid field.
else if (from === 'invalid' && to === 'saving') {
accept = true;
}
// Allow: invalid -> activating.
// Necessary to be able to correct a field that turned out to be
// invalid after the user already had moved on to the next field
// (which we explicitly allow to have a fluent UX).
else if (from === 'invalid' && to === 'activating') {
accept = true;
}
}
// If it's not against the general principle, then here are more
// disallowed cases to check.
if (accept) {
var activeField;
var activeFieldState;
// Ensure only one field (editor) at a time is active … but allow a
// user to hop from one field to the next, even if we still have to
// start saving the field that is currently active: assume it will be
// valid, to allow for a fluent UX. (If it turns out to be invalid,
// this block of code also handles that.)
if ((this.readyFieldStates.indexOf(from) !== -1 || from === 'invalid') && this.activeFieldStates.indexOf(to) !== -1) {
activeField = this.model.get('activeField');
if (activeField && activeField !== fieldModel) {
activeFieldState = activeField.get('state');
// Allow the state change. If the state of the active field is:
// - 'activating' or 'active': change it to 'candidate'
// - 'changed' or 'invalid': change it to 'saving'
// - 'saving' or 'saved': don't do anything.
if (this.activeFieldStates.indexOf(activeFieldState) !== -1) {
activeField.set('state', 'candidate');
}
else if (activeFieldState === 'changed' || activeFieldState === 'invalid') {
activeField.set('state', 'saving');
}
// If the field that's being activated is in fact already in the
// invalid state (which can only happen because above we allowed
// the user to move on to another field to allow for a fluent UX;
// we assumed it would be saved successfully), then we shouldn't
// allow the field to enter the 'activating' state, instead, we
// simply change the active editor. All guarantees and
// assumptions for this field still hold!
if (from === 'invalid') {
this.model.set('activeField', fieldModel);
accept = false;
}
// Do not reject: the field is either in the 'candidate' or
// 'highlighted' state and we allow it to enter the 'activating'
// state!
}
}
// Reject going from activating/active to candidate because of a
// mouseleave.
else if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') {
if (context && context.reason === 'mouseleave') {
accept = false;
}
}
// When attempting to stop editing a changed/invalid property, ask for
// confirmation.
else if ((from === 'changed' || from === 'invalid') && to === 'candidate') {
if (context && context.reason === 'mouseleave') {
accept = false;
}
else {
// Check whether the transition has been confirmed?
if (context && context.confirmed) {
accept = true;
}
}
}
}
}
return accept;
},
/**
* Sets up the in-place editor for the given field.
*
* Must happen before the fieldModel's state is changed to 'candidate'.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The field for which an in-place editor must be set up.
*/
setupEditor: function (fieldModel) {
// Get the corresponding entity toolbar.
var entityModel = fieldModel.get('entity');
var entityToolbarView = entityModel.toolbarView;
// Get the field toolbar DOM root from the entity toolbar.
var fieldToolbarRoot = entityToolbarView.getToolbarRoot();
// Create in-place editor.
var editorName = fieldModel.get('metadata').editor;
var editorModel = new Drupal.quickedit.EditorModel();
var editorView = new Drupal.quickedit.editors[editorName]({
el: $(fieldModel.get('el')),
model: editorModel,
fieldModel: fieldModel
});
// Create in-place editor's toolbar for this field — stored inside the
// entity toolbar, the entity toolbar will position itself appropriately
// above (or below) the edited element.
var toolbarView = new Drupal.quickedit.FieldToolbarView({
el: fieldToolbarRoot,
model: fieldModel,
$editedElement: $(editorView.getEditedElement()),
editorView: editorView,
entityModel: entityModel
});
// Create decoration for edited element: padding if necessary, sets
// classes on the element to style it according to the current state.
var decorationView = new Drupal.quickedit.FieldDecorationView({
el: $(editorView.getEditedElement()),
model: fieldModel,
editorView: editorView
});
// Track these three views in FieldModel so that we can tear them down
// correctly.
fieldModel.editorView = editorView;
fieldModel.toolbarView = toolbarView;
fieldModel.decorationView = decorationView;
},
/**
* Tears down the in-place editor for the given field.
*
* Must happen after the fieldModel's state is changed to 'inactive'.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The field for which an in-place editor must be torn down.
*/
teardownEditor: function (fieldModel) {
// Early-return if this field was not yet decorated.
if (typeof fieldModel.editorView === 'undefined') {
return;
}
// Unbind event handlers; remove toolbar element; delete toolbar view.
fieldModel.toolbarView.remove();
delete fieldModel.toolbarView;
// Unbind event handlers; delete decoration view. Don't remove the element
// because that would remove the field itself.
fieldModel.decorationView.remove();
delete fieldModel.decorationView;
// Unbind event handlers; delete editor view. Don't remove the element
// because that would remove the field itself.
fieldModel.editorView.remove();
delete fieldModel.editorView;
},
/**
* Asks the user to confirm whether he wants to stop editing via a modal.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* An instance of the EntityModel class.
*
* @see Drupal.quickedit.AppView#acceptEditorStateChange
*/
confirmEntityDeactivation: function (entityModel) {
var that = this;
var discardDialog;
function closeDiscardDialog(action) {
discardDialog.close(action);
// The active modal has been removed.
that.model.set('activeModal', null);
// If the targetState is saving, the field must be saved, then the
// entity must be saved.
if (action === 'save') {
entityModel.set('state', 'committing', {confirmed: true});
}
else {
entityModel.set('state', 'deactivating', {confirmed: true});
// Editing has been canceled and the changes will not be saved. Mark
// the page for reload if the entityModel declares that it requires
// a reload.
if (entityModel.get('reload')) {
reload = true;
entityModel.set('reload', false);
}
}
}
// Only instantiate if there isn't a modal instance visible yet.
if (!this.model.get('activeModal')) {
var $unsavedChanges = $('<div>' + Drupal.t('You have unsaved changes') + '</div>');
discardDialog = Drupal.dialog($unsavedChanges.get(0), {
title: Drupal.t('Discard changes?'),
dialogClass: 'quickedit-discard-modal',
resizable: false,
buttons: [
{
text: Drupal.t('Save'),
click: function () {
closeDiscardDialog('save');
},
primary: true
},
{
text: Drupal.t('Discard changes'),
click: function () {
closeDiscardDialog('discard');
}
}
],
// Prevent this modal from being closed without the user making a
// choice as per http://stackoverflow.com/a/5438771.
closeOnEscape: false,
create: function () {
$(this).parent().find('.ui-dialog-titlebar-close').remove();
},
beforeClose: false,
close: function (event) {
// Automatically destroy the DOM element that was used for the
// dialog.
$(event.target).remove();
}
});
this.model.set('activeModal', discardDialog);
discardDialog.showModal();
}
},
/**
* Reacts to field state changes; tracks global state.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The `fieldModel` holding the state.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
editorStateChange: function (fieldModel, state) {
var from = fieldModel.previous('state');
var to = state;
// Keep track of the highlighted field in the global state.
if (_.indexOf(this.singleFieldStates, to) !== -1 && this.model.get('highlightedField') !== fieldModel) {
this.model.set('highlightedField', fieldModel);
}
else if (this.model.get('highlightedField') === fieldModel && to === 'candidate') {
this.model.set('highlightedField', null);
}
// Keep track of the active field in the global state.
if (_.indexOf(this.activeFieldStates, to) !== -1 && this.model.get('activeField') !== fieldModel) {
this.model.set('activeField', fieldModel);
}
else if (this.model.get('activeField') === fieldModel && to === 'candidate') {
// Discarded if it transitions from a changed state to 'candidate'.
if (from === 'changed' || from === 'invalid') {
fieldModel.editorView.revert();
}
this.model.set('activeField', null);
}
},
/**
* Render an updated field (a field whose 'html' attribute changed).
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The FieldModel whose 'html' attribute changed.
* @param {string} html
* The updated 'html' attribute.
* @param {object} options
* An object with the following keys:
* @param {bool} options.propagation
* Whether this change to the 'html' attribute occurred because of the
* propagation of changes to another instance of this field.
*/
renderUpdatedField: function (fieldModel, html, options) {
// Get data necessary to rerender property before it is unavailable.
var $fieldWrapper = $(fieldModel.get('el'));
var $context = $fieldWrapper.parent();
var renderField = function () {
// Destroy the field model; this will cause all attached views to be
// destroyed too, and removal from all collections in which it exists.
fieldModel.destroy();
// Replace the old content with the new content.
$fieldWrapper.replaceWith(html);
// Attach behaviors again to the modified piece of HTML; this will
// create a new field model and call rerenderedFieldToCandidate() with
// it.
Drupal.attachBehaviors($context.get(0));
};
// When propagating the changes of another instance of this field, this
// field is not being actively edited and hence no state changes are
// necessary. So: only update the state of this field when the rerendering
// of this field happens not because of propagation, but because it is
// being edited itself.
if (!options.propagation) {
// Deferred because renderUpdatedField is reacting to a field model
// change event, and we want to make sure that event fully propagates
// before making another change to the same model.
_.defer(function () {
// First set the state to 'candidate', to allow all attached views to
// clean up all their "active state"-related changes.
fieldModel.set('state', 'candidate');
// Similarly, the above .set() call's change event must fully
// propagate before calling it again.
_.defer(function () {
// Set the field's state to 'inactive', to enable the updating of
// its DOM value.
fieldModel.set('state', 'inactive', {reason: 'rerender'});
renderField();
});
});
}
else {
renderField();
}
},
/**
* Propagates changes to an updated field to all instances of that field.
*
* @param {Drupal.quickedit.FieldModel} updatedField
* The FieldModel whose 'html' attribute changed.
* @param {string} html
* The updated 'html' attribute.
* @param {object} options
* An object with the following keys:
* @param {bool} options.propagation
* Whether this change to the 'html' attribute occurred because of the
* propagation of changes to another instance of this field.
*
* @see Drupal.quickedit.AppView#renderUpdatedField
*/
propagateUpdatedField: function (updatedField, html, options) {
// Don't propagate field updates that themselves were caused by
// propagation.
if (options.propagation) {
return;
}
var htmlForOtherViewModes = updatedField.get('htmlForOtherViewModes');
Drupal.quickedit.collections.fields
// Find all instances of fields that display the same logical field
// (same entity, same field, just a different instance and maybe a
// different view mode).
.where({logicalFieldID: updatedField.get('logicalFieldID')})
.forEach(function (field) {
// Ignore the field that was already updated.
if (field === updatedField) {
return;
}
// If this other instance of the field has the same view mode, we can
// update it easily.
else if (field.getViewMode() === updatedField.getViewMode()) {
field.set('html', updatedField.get('html'));
}
// If this other instance of the field has a different view mode, and
// that is one of the view modes for which a re-rendered version is
// available (and that should be the case unless this field was only
// added to the page after editing of the updated field began), then
// use that view mode's re-rendered version.
else {
if (field.getViewMode() in htmlForOtherViewModes) {
field.set('html', htmlForOtherViewModes[field.getViewMode()], {propagation: true});
}
}
});
},
/**
* If the new in-place editable field is for the entity that's currently
* being edited, then transition it to the 'candidate' state.
*
* This happens when a field was modified, saved and hence rerendered.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* A field that was just added to the collection of fields.
*/
rerenderedFieldToCandidate: function (fieldModel) {
var activeEntity = Drupal.quickedit.collections.entities.findWhere({isActive: true});
// Early-return if there is no active entity.
if (!activeEntity) {
return;
}
// If the field's entity is the active entity, make it a candidate.
if (fieldModel.get('entity') === activeEntity) {
this.setupEditor(fieldModel);
fieldModel.set('state', 'candidate');
}
},
/**
* EntityModel Collection change handler.
*
* Handler is called `change:isActive` and enforces a single active entity.
*
* @param {Drupal.quickedit.EntityModel} changedEntityModel
* The entityModel instance whose active state has changed.
*/
enforceSingleActiveEntity: function (changedEntityModel) {
// When an entity is deactivated, we don't need to enforce anything.
if (changedEntityModel.get('isActive') === false) {
return;
}
// This entity was activated; deactivate all other entities.
changedEntityModel.collection.chain()
.filter(function (entityModel) {
return entityModel.get('isActive') === true && entityModel !== changedEntityModel;
})
.each(function (entityModel) {
entityModel.set('state', 'deactivating');
});
}
});
}(jQuery, _, Backbone, Drupal));
;
/**
* @file
* A Backbone View that decorates the in-place edited element.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.quickedit.FieldDecorationView = Backbone.View.extend(/** @lends Drupal.quickedit.FieldDecorationView# */{
/**
* @type {null}
*/
_widthAttributeIsEmpty: null,
/**
* @type {object}
*/
events: {
'mouseenter.quickedit': 'onMouseEnter',
'mouseleave.quickedit': 'onMouseLeave',
'click': 'onClick',
'tabIn.quickedit': 'onMouseEnter',
'tabOut.quickedit': 'onMouseLeave'
},
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.EditorView} options.editorView
* The editor object view.
*/
initialize: function (options) {
this.editorView = options.editorView;
this.listenTo(this.model, 'change:state', this.stateChange);
this.listenTo(this.model, 'change:isChanged change:inTempStore', this.renderChanged);
},
/**
* @inheritdoc
*/
remove: function () {
// The el property is the field, which should not be removed. Remove the
// pointer to it, then call Backbone.View.prototype.remove().
this.setElement();
Backbone.View.prototype.remove.call(this);
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} model
* The `FieldModel` model.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
stateChange: function (model, state) {
var from = model.previous('state');
var to = state;
switch (to) {
case 'inactive':
this.undecorate();
break;
case 'candidate':
this.decorate();
if (from !== 'inactive') {
this.stopHighlight();
if (from !== 'highlighted') {
this.model.set('isChanged', false);
this.stopEdit();
}
}
this._unpad();
break;
case 'highlighted':
this.startHighlight();
break;
case 'activating':
// NOTE: this state is not used by every editor! It's only used by
// those that need to interact with the server.
this.prepareEdit();
break;
case 'active':
if (from !== 'activating') {
this.prepareEdit();
}
if (this.editorView.getQuickEditUISettings().padding) {
this._pad();
}
break;
case 'changed':
this.model.set('isChanged', true);
break;
case 'saving':
break;
case 'saved':
break;
case 'invalid':
break;
}
},
/**
* Adds a class to the edited element that indicates whether the field has
* been changed by the user (i.e. locally) or the field has already been
* changed and stored before by the user (i.e. remotely, stored in
* PrivateTempStore).
*/
renderChanged: function () {
this.$el.toggleClass('quickedit-changed', this.model.get('isChanged') || this.model.get('inTempStore'));
},
/**
* Starts hover; transitions to 'highlight' state.
*
* @param {jQuery.Event} event
* The mouse event.
*/
onMouseEnter: function (event) {
var that = this;
that.model.set('state', 'highlighted');
event.stopPropagation();
},
/**
* Stops hover; transitions to 'candidate' state.
*
* @param {jQuery.Event} event
* The mouse event.
*/
onMouseLeave: function (event) {
var that = this;
that.model.set('state', 'candidate', {reason: 'mouseleave'});
event.stopPropagation();
},
/**
* Transition to 'activating' stage.
*
* @param {jQuery.Event} event
* The click event.
*/
onClick: function (event) {
this.model.set('state', 'activating');
event.preventDefault();
event.stopPropagation();
},
/**
* Adds classes used to indicate an elements editable state.
*/
decorate: function () {
this.$el.addClass('quickedit-candidate quickedit-editable');
},
/**
* Removes classes used to indicate an elements editable state.
*/
undecorate: function () {
this.$el.removeClass('quickedit-candidate quickedit-editable quickedit-highlighted quickedit-editing');
},
/**
* Adds that class that indicates that an element is highlighted.
*/
startHighlight: function () {
// Animations.
var that = this;
// Use a timeout to grab the next available animation frame.
that.$el.addClass('quickedit-highlighted');
},
/**
* Removes the class that indicates that an element is highlighted.
*/
stopHighlight: function () {
this.$el.removeClass('quickedit-highlighted');
},
/**
* Removes the class that indicates that an element as editable.
*/
prepareEdit: function () {
this.$el.addClass('quickedit-editing');
// Allow the field to be styled differently while editing in a pop-up
// in-place editor.
if (this.editorView.getQuickEditUISettings().popup) {
this.$el.addClass('quickedit-editor-is-popup');
}
},
/**
* Removes the class that indicates that an element is being edited.
*
* Reapplies the class that indicates that a candidate editable element is
* again available to be edited.
*/
stopEdit: function () {
this.$el.removeClass('quickedit-highlighted quickedit-editing');
// Done editing in a pop-up in-place editor; remove the class.
if (this.editorView.getQuickEditUISettings().popup) {
this.$el.removeClass('quickedit-editor-is-popup');
}
// Make the other editors show up again.
$('.quickedit-candidate').addClass('quickedit-editable');
},
/**
* Adds padding around the editable element to make it pop visually.
*/
_pad: function () {
// Early return if the element has already been padded.
if (this.$el.data('quickedit-padded')) {
return;
}
var self = this;
// Add 5px padding for readability. This means we'll freeze the current
// width and *then* add 5px padding, hence ensuring the padding is added
// "on the outside".
// 1) Freeze the width (if it's not already set); don't use animations.
if (this.$el[0].style.width === '') {
this._widthAttributeIsEmpty = true;
this.$el
.addClass('quickedit-animate-disable-width')
.css('width', this.$el.width());
}
// 2) Add padding; use animations.
var posProp = this._getPositionProperties(this.$el);
setTimeout(function () {
// Re-enable width animations (padding changes affect width too!).
self.$el.removeClass('quickedit-animate-disable-width');
// Pad the editable.
self.$el
.css({
'position': 'relative',
'top': posProp.top - 5 + 'px',
'left': posProp.left - 5 + 'px',
'padding-top': posProp['padding-top'] + 5 + 'px',
'padding-left': posProp['padding-left'] + 5 + 'px',
'padding-right': posProp['padding-right'] + 5 + 'px',
'padding-bottom': posProp['padding-bottom'] + 5 + 'px',
'margin-bottom': posProp['margin-bottom'] - 10 + 'px'
})
.data('quickedit-padded', true);
}, 0);
},
/**
* Removes the padding around the element being edited when editing ceases.
*/
_unpad: function () {
// Early return if the element has not been padded.
if (!this.$el.data('quickedit-padded')) {
return;
}
var self = this;
// 1) Set the empty width again.
if (this._widthAttributeIsEmpty) {
this.$el
.addClass('quickedit-animate-disable-width')
.css('width', '');
}
// 2) Remove padding; use animations (these will run simultaneously with)
// the fading out of the toolbar as its gets removed).
var posProp = this._getPositionProperties(this.$el);
setTimeout(function () {
// Re-enable width animations (padding changes affect width too!).
self.$el.removeClass('quickedit-animate-disable-width');
// Unpad the editable.
self.$el
.css({
'position': 'relative',
'top': posProp.top + 5 + 'px',
'left': posProp.left + 5 + 'px',
'padding-top': posProp['padding-top'] - 5 + 'px',
'padding-left': posProp['padding-left'] - 5 + 'px',
'padding-right': posProp['padding-right'] - 5 + 'px',
'padding-bottom': posProp['padding-bottom'] - 5 + 'px',
'margin-bottom': posProp['margin-bottom'] + 10 + 'px'
});
}, 0);
// Remove the marker that indicates that this field has padding. This is
// done outside the timed out function above so that we don't get numerous
// queued functions that will remove padding before the data marker has
// been removed.
this.$el.removeData('quickedit-padded');
},
/**
* Gets the top and left properties of an element.
*
* Convert extraneous values and information into numbers ready for
* subtraction.
*
* @param {jQuery} $e
* The element to get position properties from.
*
* @return {object}
* An object containing css values for the needed properties.
*/
_getPositionProperties: function ($e) {
var p;
var r = {};
var props = [
'top', 'left', 'bottom', 'right',
'padding-top', 'padding-left', 'padding-right', 'padding-bottom',
'margin-bottom'
];
var propCount = props.length;
for (var i = 0; i < propCount; i++) {
p = props[i];
r[p] = parseInt(this._replaceBlankPosition($e.css(p)), 10);
}
return r;
},
/**
* Replaces blank or 'auto' CSS `position: <value>` values with "0px".
*
* @param {string} [pos]
* The value for a CSS position declaration.
*
* @return {string}
* A CSS value that is valid for `position`.
*/
_replaceBlankPosition: function (pos) {
if (pos === 'auto' || !pos) {
pos = '0px';
}
return pos;
}
});
})(jQuery, Backbone, Drupal);
;
/**
* @file
* A Backbone view that decorates the in-place editable entity.
*/
(function (Drupal, $, Backbone) {
'use strict';
Drupal.quickedit.EntityDecorationView = Backbone.View.extend(/** @lends Drupal.quickedit.EntityDecorationView# */{
/**
* Associated with the DOM root node of an editable entity.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
/**
* @inheritdoc
*/
render: function () {
this.$el.toggleClass('quickedit-entity-active', this.model.get('isActive'));
},
/**
* @inheritdoc
*/
remove: function () {
this.setElement(null);
Backbone.View.prototype.remove.call(this);
}
});
}(Drupal, jQuery, Backbone));
;
/**
* @file
* A Backbone View that provides an entity level toolbar.
*/
(function ($, _, Backbone, Drupal, debounce) {
'use strict';
Drupal.quickedit.EntityToolbarView = Backbone.View.extend(/** @lends Drupal.quickedit.EntityToolbarView# */{
/**
* @type {jQuery}
*/
_fieldToolbarRoot: null,
/**
* @return {object}
* A map of events.
*/
events: function () {
var map = {
'click button.action-save': 'onClickSave',
'click button.action-cancel': 'onClickCancel',
'mouseenter': 'onMouseenter'
};
return map;
},
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options to construct the view.
* @param {Drupal.quickedit.AppModel} options.appModel
* A quickedit `AppModel` to use in the view.
*/
initialize: function (options) {
var that = this;
this.appModel = options.appModel;
this.$entity = $(this.model.get('el'));
// Rerender whenever the entity state changes.
this.listenTo(this.model, 'change:isActive change:isDirty change:state', this.render);
// Also rerender whenever a different field is highlighted or activated.
this.listenTo(this.appModel, 'change:highlightedField change:activeField', this.render);
// Rerender when a field of the entity changes state.
this.listenTo(this.model.get('fields'), 'change:state', this.fieldStateChange);
// Reposition the entity toolbar as the viewport and the position within
// the viewport changes.
$(window).on('resize.quickedit scroll.quickedit drupalViewportOffsetChange.quickedit', debounce($.proxy(this.windowChangeHandler, this), 150));
// Adjust the fence placement within which the entity toolbar may be
// positioned.
$(document).on('drupalViewportOffsetChange.quickedit', function (event, offsets) {
if (that.$fence) {
that.$fence.css(offsets);
}
});
// Set the entity toolbar DOM element as the el for this view.
var $toolbar = this.buildToolbarEl();
this.setElement($toolbar);
this._fieldToolbarRoot = $toolbar.find('.quickedit-toolbar-field').get(0);
// Initial render.
this.render();
},
/**
* @inheritdoc
*
* @return {Drupal.quickedit.EntityToolbarView}
* The entity toolbar view.
*/
render: function () {
if (this.model.get('isActive')) {
// If the toolbar container doesn't exist, create it.
var $body = $('body');
if ($body.children('#quickedit-entity-toolbar').length === 0) {
$body.append(this.$el);
}
// The fence will define a area on the screen that the entity toolbar
// will be position within.
if ($body.children('#quickedit-toolbar-fence').length === 0) {
this.$fence = $(Drupal.theme('quickeditEntityToolbarFence'))
.css(Drupal.displace())
.appendTo($body);
}
// Adds the entity title to the toolbar.
this.label();
// Show the save and cancel buttons.
this.show('ops');
// If render is being called and the toolbar is already visible, just
// reposition it.
this.position();
}
// The save button text and state varies with the state of the entity
// model.
var $button = this.$el.find('.quickedit-button.action-save');
var isDirty = this.model.get('isDirty');
// Adjust the save button according to the state of the model.
switch (this.model.get('state')) {
// Quick editing is active, but no field is being edited.
case 'opened':
// The saving throbber is not managed by AJAX system. The
// EntityToolbarView manages this visual element.
$button
.removeClass('action-saving icon-throbber icon-end')
.text(Drupal.t('Save'))
.removeAttr('disabled')
.attr('aria-hidden', !isDirty);
break;
// The changes to the fields of the entity are being committed.
case 'committing':
$button
.addClass('action-saving icon-throbber icon-end')
.text(Drupal.t('Saving'))
.attr('disabled', 'disabled');
break;
default:
$button.attr('aria-hidden', true);
break;
}
return this;
},
/**
* @inheritdoc
*/
remove: function () {
// Remove additional DOM elements controlled by this View.
this.$fence.remove();
// Stop listening to additional events.
$(window).off('resize.quickedit scroll.quickedit drupalViewportOffsetChange.quickedit');
$(document).off('drupalViewportOffsetChange.quickedit');
Backbone.View.prototype.remove.call(this);
},
/**
* Repositions the entity toolbar on window scroll and resize.
*
* @param {jQuery.Event} event
* The scroll or resize event.
*/
windowChangeHandler: function (event) {
this.position();
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} model
* The `FieldModel` model.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
fieldStateChange: function (model, state) {
switch (state) {
case 'active':
this.render();
break;
case 'invalid':
this.render();
break;
}
},
/**
* Uses the jQuery.ui.position() method to position the entity toolbar.
*
* @param {HTMLElement} [element]
* The element against which the entity toolbar is positioned.
*/
position: function (element) {
clearTimeout(this.timer);
var that = this;
// Vary the edge of the positioning according to the direction of language
// in the document.
var edge = (document.documentElement.dir === 'rtl') ? 'right' : 'left';
// A time unit to wait until the entity toolbar is repositioned.
var delay = 0;
// Determines what check in the series of checks below should be
// evaluated.
var check = 0;
// When positioned against an active field that has padding, we should
// ignore that padding when positioning the toolbar, to not unnecessarily
// move the toolbar horizontally, which feels annoying.
var horizontalPadding = 0;
var of;
var activeField;
var highlightedField;
// There are several elements in the page that the entity toolbar might be
// positioned against. They are considered below in a priority order.
do {
switch (check) {
case 0:
// Position against a specific element.
of = element;
break;
case 1:
// Position against a form container.
activeField = Drupal.quickedit.app.model.get('activeField');
of = activeField && activeField.editorView && activeField.editorView.$formContainer && activeField.editorView.$formContainer.find('.quickedit-form');
break;
case 2:
// Position against an active field.
of = activeField && activeField.editorView && activeField.editorView.getEditedElement();
if (activeField && activeField.editorView && activeField.editorView.getQuickEditUISettings().padding) {
horizontalPadding = 5;
}
break;
case 3:
// Position against a highlighted field.
highlightedField = Drupal.quickedit.app.model.get('highlightedField');
of = highlightedField && highlightedField.editorView && highlightedField.editorView.getEditedElement();
delay = 250;
break;
default:
var fieldModels = this.model.get('fields').models;
var topMostPosition = 1000000;
var topMostField = null;
// Position against the topmost field.
for (var i = 0; i < fieldModels.length; i++) {
var pos = fieldModels[i].get('el').getBoundingClientRect().top;
if (pos < topMostPosition) {
topMostPosition = pos;
topMostField = fieldModels[i];
}
}
of = topMostField.get('el');
delay = 50;
break;
}
// Prepare to check the next possible element to position against.
check++;
} while (!of);
/**
* Refines the positioning algorithm of jquery.ui.position().
*
* Invoked as the 'using' callback of jquery.ui.position() in
* positionToolbar().
*
* @param {*} view
* The view the positions will be calculated from.
* @param {object} suggested
* A hash of top and left values for the position that should be set. It
* can be forwarded to .css() or .animate().
* @param {object} info
* The position and dimensions of both the 'my' element and the 'of'
* elements, as well as calculations to their relative position. This
* object contains the following properties:
* @param {object} info.element
* A hash that contains information about the HTML element that will be
* positioned. Also known as the 'my' element.
* @param {object} info.target
* A hash that contains information about the HTML element that the
* 'my' element will be positioned against. Also known as the 'of'
* element.
*/
function refinePosition(view, suggested, info) {
// Determine if the pointer should be on the top or bottom.
var isBelow = suggested.top > info.target.top;
info.element.element.toggleClass('quickedit-toolbar-pointer-top', isBelow);
// Don't position the toolbar past the first or last editable field if
// the entity is the target.
if (view.$entity[0] === info.target.element[0]) {
// Get the first or last field according to whether the toolbar is
// above or below the entity.
var $field = view.$entity.find('.quickedit-editable').eq((isBelow) ? -1 : 0);
if ($field.length > 0) {
suggested.top = (isBelow) ? ($field.offset().top + $field.outerHeight(true)) : $field.offset().top - info.element.element.outerHeight(true);
}
}
// Don't let the toolbar go outside the fence.
var fenceTop = view.$fence.offset().top;
var fenceHeight = view.$fence.height();
var toolbarHeight = info.element.element.outerHeight(true);
if (suggested.top < fenceTop) {
suggested.top = fenceTop;
}
else if ((suggested.top + toolbarHeight) > (fenceTop + fenceHeight)) {
suggested.top = fenceTop + fenceHeight - toolbarHeight;
}
// Position the toolbar.
info.element.element.css({
left: Math.floor(suggested.left),
top: Math.floor(suggested.top)
});
}
/**
* Calls the jquery.ui.position() method on the $el of this view.
*/
function positionToolbar() {
that.$el
.position({
my: edge + ' bottom',
// Move the toolbar 1px towards the start edge of the 'of' element,
// plus any horizontal padding that may have been added to the
// element that is being added, to prevent unwanted horizontal
// movement.
at: edge + '+' + (1 + horizontalPadding) + ' top',
of: of,
collision: 'flipfit',
using: refinePosition.bind(null, that),
within: that.$fence
})
// Resize the toolbar to match the dimensions of the field, up to a
// maximum width that is equal to 90% of the field's width.
.css({
'max-width': (document.documentElement.clientWidth < 450) ? document.documentElement.clientWidth : 450,
// Set a minimum width of 240px for the entity toolbar, or the width
// of the client if it is less than 240px, so that the toolbar
// never folds up into a squashed and jumbled mess.
'min-width': (document.documentElement.clientWidth < 240) ? document.documentElement.clientWidth : 240,
'width': '100%'
});
}
// Uses the jQuery.ui.position() method. Use a timeout to move the toolbar
// only after the user has focused on an editable for 250ms. This prevents
// the toolbar from jumping around the screen.
this.timer = setTimeout(function () {
// Render the position in the next execution cycle, so that animations
// on the field have time to process. This is not strictly speaking, a
// guarantee that all animations will be finished, but it's a simple
// way to get better positioning without too much additional code.
_.defer(positionToolbar);
}, delay);
},
/**
* Set the model state to 'saving' when the save button is clicked.
*
* @param {jQuery.Event} event
* The click event.
*/
onClickSave: function (event) {
event.stopPropagation();
event.preventDefault();
// Save the model.
this.model.set('state', 'committing');
},
/**
* Sets the model state to candidate when the cancel button is clicked.
*
* @param {jQuery.Event} event
* The click event.
*/
onClickCancel: function (event) {
event.preventDefault();
this.model.set('state', 'deactivating');
},
/**
* Clears the timeout that will eventually reposition the entity toolbar.
*
* Without this, it may reposition itself, away from the user's cursor!
*
* @param {jQuery.Event} event
* The mouse event.
*/
onMouseenter: function (event) {
clearTimeout(this.timer);
},
/**
* Builds the entity toolbar HTML; attaches to DOM; sets starting position.
*
* @return {jQuery}
* The toolbar element.
*/
buildToolbarEl: function () {
var $toolbar = $(Drupal.theme('quickeditEntityToolbar', {
id: 'quickedit-entity-toolbar'
}));
$toolbar
.find('.quickedit-toolbar-entity')
// Append the "ops" toolgroup into the toolbar.
.prepend(Drupal.theme('quickeditToolgroup', {
classes: ['ops'],
buttons: [
{
label: Drupal.t('Save'),
type: 'submit',
classes: 'action-save quickedit-button icon',
attributes: {
'aria-hidden': true
}
},
{
label: Drupal.t('Close'),
classes: 'action-cancel quickedit-button icon icon-close icon-only'
}
]
}));
// Give the toolbar a sensible starting position so that it doesn't
// animate on to the screen from a far off corner.
$toolbar
.css({
left: this.$entity.offset().left,
top: this.$entity.offset().top
});
return $toolbar;
},
/**
* Returns the DOM element that fields will attach their toolbars to.
*
* @return {jQuery}
* The DOM element that fields will attach their toolbars to.
*/
getToolbarRoot: function () {
return this._fieldToolbarRoot;
},
/**
* Generates a state-dependent label for the entity toolbar.
*/
label: function () {
// The entity label.
var label = '';
var entityLabel = this.model.get('label');
// Label of an active field, if it exists.
var activeField = Drupal.quickedit.app.model.get('activeField');
var activeFieldLabel = activeField && activeField.get('metadata').label;
// Label of a highlighted field, if it exists.
var highlightedField = Drupal.quickedit.app.model.get('highlightedField');
var highlightedFieldLabel = highlightedField && highlightedField.get('metadata').label;
// The label is constructed in a priority order.
if (activeFieldLabel) {
label = Drupal.theme('quickeditEntityToolbarLabel', {
entityLabel: entityLabel,
fieldLabel: activeFieldLabel
});
}
else if (highlightedFieldLabel) {
label = Drupal.theme('quickeditEntityToolbarLabel', {
entityLabel: entityLabel,
fieldLabel: highlightedFieldLabel
});
}
else {
// @todo Add XSS regression test coverage in https://www.drupal.org/node/2547437
label = Drupal.checkPlain(entityLabel);
}
this.$el
.find('.quickedit-toolbar-label')
.html(label);
},
/**
* Adds classes to a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
* @param {string} classes
* A string of space-delimited class names that will be applied to the
* wrapping element of the toolbar group.
*/
addClass: function (toolgroup, classes) {
this._find(toolgroup).addClass(classes);
},
/**
* Removes classes from a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
* @param {string} classes
* A string of space-delimited class names that will be removed from the
* wrapping element of the toolbar group.
*/
removeClass: function (toolgroup, classes) {
this._find(toolgroup).removeClass(classes);
},
/**
* Finds a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*
* @return {jQuery}
* The toolgroup DOM element.
*/
_find: function (toolgroup) {
return this.$el.find('.quickedit-toolbar .quickedit-toolgroup.' + toolgroup);
},
/**
* Shows a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*/
show: function (toolgroup) {
this.$el.removeClass('quickedit-animate-invisible');
}
});
})(jQuery, _, Backbone, Drupal, Drupal.debounce);
;
/**
* @file
* A Backbone View that provides a dynamic contextual link.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.quickedit.ContextualLinkView = Backbone.View.extend(/** @lends Drupal.quickedit.ContextualLinkView# */{
/**
* Define all events to listen to.
*
* @return {object}
* A map of events.
*/
events: function () {
// Prevents delay and simulated mouse events.
function touchEndToClick(event) {
event.preventDefault();
event.target.click();
}
return {
'click a': function (event) {
event.preventDefault();
this.model.set('state', 'launching');
},
'touchEnd a': touchEndToClick
};
},
/**
* Create a new contextual link view.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.EntityModel} options.model
* The associated entity's model.
* @param {Drupal.quickedit.AppModel} options.appModel
* The application state model.
* @param {object} options.strings
* The strings for the "Quick edit" link.
*/
initialize: function (options) {
// Insert the text of the quick edit toggle.
this.$el.find('a').text(options.strings.quickEdit);
// Initial render.
this.render();
// Re-render whenever this entity's isActive attribute changes.
this.listenTo(this.model, 'change:isActive', this.render);
},
/**
* Render function for the contextual link view.
*
* @param {Drupal.quickedit.EntityModel} entityModel
* The associated `EntityModel`.
* @param {bool} isActive
* Whether the in-place editor is active or not.
*
* @return {Drupal.quickedit.ContextualLinkView}
* The `ContextualLinkView` in question.
*/
render: function (entityModel, isActive) {
this.$el.find('a').attr('aria-pressed', isActive);
// Hides the contextual links if an in-place editor is active.
this.$el.closest('.contextual').toggle(!isActive);
return this;
}
});
})(jQuery, Backbone, Drupal);
;
/**
* @file
* A Backbone View that provides an interactive toolbar (1 per in-place editor).
*/
(function ($, _, Backbone, Drupal) {
'use strict';
Drupal.quickedit.FieldToolbarView = Backbone.View.extend(/** @lends Drupal.quickedit.FieldToolbarView# */{
/**
* The edited element, as indicated by EditorView.getEditedElement.
*
* @type {jQuery}
*/
$editedElement: null,
/**
* A reference to the in-place editor.
*
* @type {Drupal.quickedit.EditorView}
*/
editorView: null,
/**
* @type {string}
*/
_id: null,
/**
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options object to construct the field toolbar.
* @param {jQuery} options.$editedElement
* The element being edited.
* @param {Drupal.quickedit.EditorView} options.editorView
* The EditorView the toolbar belongs to.
*/
initialize: function (options) {
this.$editedElement = options.$editedElement;
this.editorView = options.editorView;
/**
* @type {jQuery}
*/
this.$root = this.$el;
// Generate a DOM-compatible ID for the form container DOM element.
this._id = 'quickedit-toolbar-for-' + this.model.id.replace(/[\/\[\]]/g, '_');
this.listenTo(this.model, 'change:state', this.stateChange);
},
/**
* @inheritdoc
*
* @return {Drupal.quickedit.FieldToolbarView}
* The current FieldToolbarView.
*/
render: function () {
// Render toolbar and set it as the view's element.
this.setElement($(Drupal.theme('quickeditFieldToolbar', {
id: this._id
})));
// Attach to the field toolbar $root element in the entity toolbar.
this.$el.prependTo(this.$root);
return this;
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} model
* The quickedit FieldModel
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
stateChange: function (model, state) {
var from = model.previous('state');
var to = state;
switch (to) {
case 'inactive':
break;
case 'candidate':
// Remove the view's existing element if we went to the 'activating'
// state or later, because it will be recreated. Not doing this would
// result in memory leaks.
if (from !== 'inactive' && from !== 'highlighted') {
this.$el.remove();
this.setElement();
}
break;
case 'highlighted':
break;
case 'activating':
this.render();
if (this.editorView.getQuickEditUISettings().fullWidthToolbar) {
this.$el.addClass('quickedit-toolbar-fullwidth');
}
if (this.editorView.getQuickEditUISettings().unifiedToolbar) {
this.insertWYSIWYGToolGroups();
}
break;
case 'active':
break;
case 'changed':
break;
case 'saving':
break;
case 'saved':
break;
case 'invalid':
break;
}
},
/**
* Insert WYSIWYG markup into the associated toolbar.
*/
insertWYSIWYGToolGroups: function () {
this.$el
.append(Drupal.theme('quickeditToolgroup', {
id: this.getFloatedWysiwygToolgroupId(),
classes: ['wysiwyg-floated', 'quickedit-animate-slow', 'quickedit-animate-invisible', 'quickedit-animate-delay-veryfast'],
buttons: []
}))
.append(Drupal.theme('quickeditToolgroup', {
id: this.getMainWysiwygToolgroupId(),
classes: ['wysiwyg-main', 'quickedit-animate-slow', 'quickedit-animate-invisible', 'quickedit-animate-delay-veryfast'],
buttons: []
}));
// Animate the toolgroups into visibility.
this.show('wysiwyg-floated');
this.show('wysiwyg-main');
},
/**
* Retrieves the ID for this toolbar's container.
*
* Only used to make sane hovering behavior possible.
*
* @return {string}
* A string that can be used as the ID for this toolbar's container.
*/
getId: function () {
return 'quickedit-toolbar-for-' + this._id;
},
/**
* Retrieves the ID for this toolbar's floating WYSIWYG toolgroup.
*
* Used to provide an abstraction for any WYSIWYG editor to plug in.
*
* @return {string}
* A string that can be used as the ID.
*/
getFloatedWysiwygToolgroupId: function () {
return 'quickedit-wysiwyg-floated-toolgroup-for-' + this._id;
},
/**
* Retrieves the ID for this toolbar's main WYSIWYG toolgroup.
*
* Used to provide an abstraction for any WYSIWYG editor to plug in.
*
* @return {string}
* A string that can be used as the ID.
*/
getMainWysiwygToolgroupId: function () {
return 'quickedit-wysiwyg-main-toolgroup-for-' + this._id;
},
/**
* Finds a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*
* @return {jQuery}
* The toolgroup element.
*/
_find: function (toolgroup) {
return this.$el.find('.quickedit-toolgroup.' + toolgroup);
},
/**
* Shows a toolgroup.
*
* @param {string} toolgroup
* A toolgroup name.
*/
show: function (toolgroup) {
var $group = this._find(toolgroup);
// Attach a transitionEnd event handler to the toolbar group so that
// update events can be triggered after the animations have ended.
$group.on(Drupal.quickedit.util.constants.transitionEnd, function (event) {
$group.off(Drupal.quickedit.util.constants.transitionEnd);
});
// The call to remove the class and start the animation must be started in
// the next animation frame or the event handler attached above won't be
// triggered.
window.setTimeout(function () {
$group.removeClass('quickedit-animate-invisible');
}, 0);
}
});
})(jQuery, _, Backbone, Drupal);
;
/**
* @file
* An abstract Backbone View that controls an in-place editor.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.quickedit.EditorView = Backbone.View.extend(/** @lends Drupal.quickedit.EditorView# */{
/**
* A base implementation that outlines the structure for in-place editors.
*
* Specific in-place editor implementations should subclass (extend) this
* View and override whichever method they deem necessary to override.
*
* Typically you would want to override this method to set the
* originalValue attribute in the FieldModel to such a value that your
* in-place editor can revert to the original value when necessary.
*
* @example
* <caption>If you override this method, you should call this
* method (the parent class' initialize()) first.</caption>
* Drupal.quickedit.EditorView.prototype.initialize.call(this, options);
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* An object with the following keys:
* @param {Drupal.quickedit.EditorModel} options.model
* The in-place editor state model.
* @param {Drupal.quickedit.FieldModel} options.fieldModel
* The field model.
*
* @see Drupal.quickedit.EditorModel
* @see Drupal.quickedit.editors.plain_text
*/
initialize: function (options) {
this.fieldModel = options.fieldModel;
this.listenTo(this.fieldModel, 'change:state', this.stateChange);
},
/**
* @inheritdoc
*/
remove: function () {
// The el property is the field, which should not be removed. Remove the
// pointer to it, then call Backbone.View.prototype.remove().
this.setElement();
Backbone.View.prototype.remove.call(this);
},
/**
* Returns the edited element.
*
* For some single cardinality fields, it may be necessary or useful to
* not in-place edit (and hence decorate) the DOM element with the
* data-quickedit-field-id attribute (which is the field's wrapper), but a
* specific element within the field's wrapper.
* e.g. using a WYSIWYG editor on a body field should happen on the DOM
* element containing the text itself, not on the field wrapper.
*
* @return {jQuery}
* A jQuery-wrapped DOM element.
*
* @see Drupal.quickedit.editors.plain_text
*/
getEditedElement: function () {
return this.$el;
},
/**
*
* @return {object}
* Returns 3 Quick Edit UI settings that depend on the in-place editor:
* - Boolean padding: indicates whether padding should be applied to the
* edited element, to guarantee legibility of text.
* - Boolean unifiedToolbar: provides the in-place editor with the ability
* to insert its own toolbar UI into Quick Edit's tightly integrated
* toolbar.
* - Boolean fullWidthToolbar: indicates whether Quick Edit's tightly
* integrated toolbar should consume the full width of the element,
* rather than being just long enough to accommodate a label.
*/
getQuickEditUISettings: function () {
return {padding: false, unifiedToolbar: false, fullWidthToolbar: false, popup: false};
},
/**
* Determines the actions to take given a change of state.
*
* @param {Drupal.quickedit.FieldModel} fieldModel
* The quickedit `FieldModel` that holds the state.
* @param {string} state
* The state of the associated field. One of
* {@link Drupal.quickedit.FieldModel.states}.
*/
stateChange: function (fieldModel, state) {
var from = fieldModel.previous('state');
var to = state;
switch (to) {
case 'inactive':
// An in-place editor view will not yet exist in this state, hence
// this will never be reached. Listed for sake of completeness.
break;
case 'candidate':
// Nothing to do for the typical in-place editor: it should not be
// visible yet. Except when we come from the 'invalid' state, then we
// clean up.
if (from === 'invalid') {
this.removeValidationErrors();
}
break;
case 'highlighted':
// Nothing to do for the typical in-place editor: it should not be
// visible yet.
break;
case 'activating':
// The user has indicated he wants to do in-place editing: if
// something needs to be loaded (CSS/JavaScript/server data/…), then
// do so at this stage, and once the in-place editor is ready,
// set the 'active' state. A "loading" indicator will be shown in the
// UI for as long as the field remains in this state.
var loadDependencies = function (callback) {
// Do the loading here.
callback();
};
loadDependencies(function () {
fieldModel.set('state', 'active');
});
break;
case 'active':
// The user can now actually use the in-place editor.
break;
case 'changed':
// Nothing to do for the typical in-place editor. The UI will show an
// indicator that the field has changed.
break;
case 'saving':
// When the user has indicated he wants to save his changes to this
// field, this state will be entered. If the previous saving attempt
// resulted in validation errors, the previous state will be
// 'invalid'. Clean up those validation errors while the user is
// saving.
if (from === 'invalid') {
this.removeValidationErrors();
}
this.save();
break;
case 'saved':
// Nothing to do for the typical in-place editor. Immediately after
// being saved, a field will go to the 'candidate' state, where it
// should no longer be visible (after all, the field will then again
// just be a *candidate* to be in-place edited).
break;
case 'invalid':
// The modified field value was attempted to be saved, but there were
// validation errors.
this.showValidationErrors();
break;
}
},
/**
* Reverts the modified value to the original, before editing started.
*/
revert: function () {
// A no-op by default; each editor should implement reverting itself.
// Note that if the in-place editor does not cause the FieldModel's
// element to be modified, then nothing needs to happen.
},
/**
* Saves the modified value in the in-place editor for this field.
*/
save: function () {
var fieldModel = this.fieldModel;
var editorModel = this.model;
var backstageId = 'quickedit_backstage-' + this.fieldModel.id.replace(/[\/\[\]\_\s]/g, '-');
function fillAndSubmitForm(value) {
var $form = $('#' + backstageId).find('form');
// Fill in the value in any <input> that isn't hidden or a submit
// button.
$form.find(':input[type!="hidden"][type!="submit"]:not(select)')
// Don't mess with the node summary.
.not('[name$="\\[summary\\]"]').val(value);
// Submit the form.
$form.find('.quickedit-form-submit').trigger('click.quickedit');
}
var formOptions = {
fieldID: this.fieldModel.get('fieldID'),
$el: this.$el,
nocssjs: true,
other_view_modes: fieldModel.findOtherViewModes(),
// Reset an existing entry for this entity in the PrivateTempStore (if
// any) when saving the field. Logically speaking, this should happen in
// a separate request because this is an entity-level operation, not a
// field-level operation. But that would require an additional request,
// that might not even be necessary: it is only when a user saves a
// first changed field for an entity that this needs to happen:
// precisely now!
reset: !this.fieldModel.get('entity').get('inTempStore')
};
var self = this;
Drupal.quickedit.util.form.load(formOptions, function (form, ajax) {
// Create a backstage area for storing forms that are hidden from view
// (hence "backstage" — since the editing doesn't happen in the form, it
// happens "directly" in the content, the form is only used for saving).
var $backstage = $(Drupal.theme('quickeditBackstage', {id: backstageId})).appendTo('body');
// Hidden forms are stuffed into the backstage container for this field.
var $form = $(form).appendTo($backstage);
// Disable the browser's HTML5 validation; we only care about server-
// side validation. (Not disabling this will actually cause problems
// because browsers don't like to set HTML5 validation errors on hidden
// forms.)
$form.prop('novalidate', true);
var $submit = $form.find('.quickedit-form-submit');
self.formSaveAjax = Drupal.quickedit.util.form.ajaxifySaving(formOptions, $submit);
function removeHiddenForm() {
Drupal.quickedit.util.form.unajaxifySaving(self.formSaveAjax);
delete self.formSaveAjax;
$backstage.remove();
}
// Successfully saved.
self.formSaveAjax.commands.quickeditFieldFormSaved = function (ajax, response, status) {
removeHiddenForm();
// First, transition the state to 'saved'.
fieldModel.set('state', 'saved');
// Second, set the 'htmlForOtherViewModes' attribute, so that when
// this field is rerendered, the change can be propagated to other
// instances of this field, which may be displayed in different view
// modes.
fieldModel.set('htmlForOtherViewModes', response.other_view_modes);
// Finally, set the 'html' attribute on the field model. This will
// cause the field to be rerendered.
fieldModel.set('html', response.data);
};
// Unsuccessfully saved; validation errors.
self.formSaveAjax.commands.quickeditFieldFormValidationErrors = function (ajax, response, status) {
removeHiddenForm();
editorModel.set('validationErrors', response.data);
fieldModel.set('state', 'invalid');
};
// The quickeditFieldForm AJAX command is only called upon loading the
// form for the first time, and when there are validation errors in the
// form; Form API then marks which form items have errors. This is
// useful for the form-based in-place editor, but pointless for any
// other: the form itself won't be visible at all anyway! So, we just
// ignore it.
self.formSaveAjax.commands.quickeditFieldForm = function () {};
fillAndSubmitForm(editorModel.get('currentValue'));
});
},
/**
* Shows validation error messages.
*
* Should be called when the state is changed to 'invalid'.
*/
showValidationErrors: function () {
var $errors = $('<div class="quickedit-validation-errors"></div>')
.append(this.model.get('validationErrors'));
this.getEditedElement()
.addClass('quickedit-validation-error')
.after($errors);
},
/**
* Cleans up validation error messages.
*
* Should be called when the state is changed to 'candidate' or 'saving'. In
* the case of the latter: the user has modified the value in the in-place
* editor again to attempt to save again. In the case of the latter: the
* invalid value was discarded.
*/
removeValidationErrors: function () {
this.getEditedElement()
.removeClass('quickedit-validation-error')
.next('.quickedit-validation-errors')
.remove();
}
});
}(jQuery, Backbone, Drupal));
;
/**
* @file
* Provides theme functions for all of Quick Edit's client-side HTML.
*/
(function ($, Drupal) {
'use strict';
/**
* Theme function for a "backstage" for the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* The id to apply to the backstage.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditBackstage = function (settings) {
var html = '';
html += '<div id="' + settings.id + '" />';
return html;
};
/**
* Theme function for a toolbar container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* the id to apply to the backstage.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditEntityToolbar = function (settings) {
var html = '';
html += '<div id="' + settings.id + '" class="quickedit quickedit-toolbar-container clearfix">';
html += '<i class="quickedit-toolbar-pointer"></i>';
html += '<div class="quickedit-toolbar-content">';
html += '<div class="quickedit-toolbar quickedit-toolbar-entity clearfix icon icon-pencil">';
html += '<div class="quickedit-toolbar-label" />';
html += '</div>';
html += '<div class="quickedit-toolbar quickedit-toolbar-field clearfix" />';
html += '</div><div class="quickedit-toolbar-lining"></div></div>';
return html;
};
/**
* Theme function for a toolbar container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.entityLabel
* The title of the active entity.
* @param {string} settings.fieldLabel
* The label of the highlighted or active field.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditEntityToolbarLabel = function (settings) {
// @todo Add XSS regression test coverage in https://www.drupal.org/node/2547437
return '<span class="field">' + Drupal.checkPlain(settings.fieldLabel) + '</span>' + Drupal.checkPlain(settings.entityLabel);
};
/**
* Element defining a containing box for the placement of the entity toolbar.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditEntityToolbarFence = function () {
return '<div id="quickedit-toolbar-fence" />';
};
/**
* Theme function for a toolbar container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* The id to apply to the toolbar container.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditFieldToolbar = function (settings) {
return '<div id="' + settings.id + '" />';
};
/**
* Theme function for a toolbar toolgroup of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} [settings.id]
* The id of the toolgroup.
* @param {string} settings.classes
* The class of the toolgroup.
* @param {Array} settings.buttons
* See {@link Drupal.theme.quickeditButtons}.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditToolgroup = function (settings) {
// Classes.
var classes = (settings.classes || []);
classes.unshift('quickedit-toolgroup');
var html = '';
html += '<div class="' + classes.join(' ') + '"';
if (settings.id) {
html += ' id="' + settings.id + '"';
}
html += '>';
html += Drupal.theme('quickeditButtons', {buttons: settings.buttons});
html += '</div>';
return html;
};
/**
* Theme function for buttons of the Quick Edit module.
*
* Can be used for the buttons both in the toolbar toolgroups and in the
* modal.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {Array} settings.buttons
* - String type: the type of the button (defaults to 'button')
* - Array classes: the classes of the button.
* - String label: the label of the button.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditButtons = function (settings) {
var html = '';
for (var i = 0; i < settings.buttons.length; i++) {
var button = settings.buttons[i];
if (!button.hasOwnProperty('type')) {
button.type = 'button';
}
// Attributes.
var attributes = [];
var attrMap = settings.buttons[i].attributes || {};
for (var attr in attrMap) {
if (attrMap.hasOwnProperty(attr)) {
attributes.push(attr + ((attrMap[attr]) ? '="' + attrMap[attr] + '"' : ''));
}
}
html += '<button type="' + button.type + '" class="' + button.classes + '"' + ' ' + attributes.join(' ') + '>';
html += button.label;
html += '</button>';
}
return html;
};
/**
* Theme function for a form container of the Quick Edit module.
*
* @param {object} settings
* Settings object used to construct the markup.
* @param {string} settings.id
* The id to apply to the toolbar container.
* @param {string} settings.loadingMsg
* The message to show while loading.
*
* @return {string}
* The corresponding HTML.
*/
Drupal.theme.quickeditFormContainer = function (settings) {
var html = '';
html += '<div id="' + settings.id + '" class="quickedit-form-container">';
html += ' <div class="quickedit-form">';
html += ' <div class="placeholder">';
html += settings.loadingMsg;
html += ' </div>';
html += ' </div>';
html += '</div>';
return html;
};
})(jQuery, Drupal);
;
(function ($) {
Drupal.behaviors.generalbehavior = {
attach: function (context, settings) {
var url = window.location.href;
if (url == 'http://piratebay.ddns.net/Knife/general') {
var cards = $(".quest-btn");
for (var i = 0; i < cards.length; i++) {
var target1 = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target1).before(cards.eq(target2));
}
console.log('Answers randomed!');
var n = 0;
var cur_score = 0;
var points = 0;
var res_score =0;
$("#quest-ans-1").on("click", function(){
n++;
$(this).blur();
if (lvl[n] == null) {
res_score = res_score+100;
alert("You win with " + res_score + " points. Good job!");
location.reload();
}
else {
cur_score = +($("#quest-score").text());
points = lvl[n]*25;
res_score = cur_score + points;
$("#quest-score").text(res_score);
$(".quest-title").text(que[n]);
$("#quest-lvl").text(lvl[n]);
$("#quest-ans-1").text(ans[n]);
$("#quest-ans-2").text(wans1[n]);
$("#quest-ans-3").text(wans2[n]);
$("#quest-ans-4").text(wans3[n]);
for (var i = 0; i < cards.length; i++) {
var target1 = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target1).before(cards.eq(target2));
}
}
});
$(".w_ans").on("click", function(){
n++;
$(this).blur();
if (lvl[n] == null) {
res_score = res_score-100;
alert("You win with " + res_score + " points. Good job!");
location.reload();
}
else {
cur_score = +($("#quest-score").text());
points = lvl[n]*25;
res_score = cur_score - points;
$("#quest-score").text(res_score);
$(".quest-title").text(que[n]);
$("#quest-lvl").text(lvl[n]);
$("#quest-ans-1").text(ans[n]);
$("#quest-ans-2").text(wans1[n]);
$("#quest-ans-3").text(wans2[n]);
$("#quest-ans-4").text(wans3[n]);
for (var i = 0; i < cards.length; i++) {
var target1 = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target1).before(cards.eq(target2));
}
}
});
}
}
};
Drupal.behaviors.ratingbehavior = {
attach: function (context, settings) {
var url = window.location.href;
if (url == 'http://piratebay.ddns.net/Knife/rate_pic') {
function random_pic(){
$('.rank-field').hide();
var pic_one = Math.floor((Math.random() * pic_url.length) + 0);
var pic_two = Math.floor((Math.random() * pic_url.length) + 0);
$('.rate_pic-left').attr("id", pic_id[pic_one]);
$('.rate_pic-left').attr("src", pic_url[pic_one]);
$('.rank-left').text('Rank: ' + pic_rating[pic_one])
$('.rate_pic-right').attr("id", pic_id[pic_two]);
$('.rate_pic-right').attr("src", pic_url[pic_two]);
$('.rank-right').text('Rank: ' + pic_rating[pic_two])
console.log(pic_one);
console.log(pic_two);
}
random_pic();
$(".img-rate_pic").on("click", function(){
$(this).data('clicked', true);
if ($('.rate_pic-left').data('clicked')) {
$('.rank-left').css("color", "green");
$('.rank-right').css("color", "red");
} else {
$('.rank-left').css("color", "red");
$('.rank-right').css("color", "green");
}
$('.rank-field').show();
setTimeout(random_pic, 1000);
});
}
}
};
})(jQuery);
;
/* ========================================================================
* Bootstrap: affix.js v3.3.7
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.7'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: alert.js v3.3.7
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.7'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
;
/* ========================================================================
* Bootstrap: button.js v3.3.7
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.7'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d).prop(d, true)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d).prop(d, false)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target).closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
// Prevent double click on radios, and the double selections (so cancellation) on checkboxes
e.preventDefault()
// The target component still receive the focus
if ($btn.is('input,button')) $btn.trigger('focus')
else $btn.find('input:visible,button:visible').first().trigger('focus')
}
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: carousel.js v3.3.7
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.7'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: collapse.js v3.3.7
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
/* jshint latedef: false */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.7'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: dropdown.js v3.3.7
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.7'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
;
/* ========================================================================
* Bootstrap: modal.js v3.3.7
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.7'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (document !== e.target &&
this.$element[0] !== e.target &&
!this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: tooltip.js v3.3.7
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.7'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function () {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
}
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var isSvg = window.SVGElement && el instanceof window.SVGElement
// Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
// See https://github.com/twbs/bootstrap/issues/20280
var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
that.$element = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
;
/* ========================================================================
* Bootstrap: popover.js v3.3.7
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.7'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
;
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.7
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.7'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
;
/* ========================================================================
* Bootstrap: tab.js v3.3.7
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.7'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
;
/* ========================================================================
* Bootstrap: transition.js v3.3.7
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
;
/**
* @file
* Attaches behaviors for Drupal's active link marking.
*/
(function (Drupal, drupalSettings) {
'use strict';
/**
* Append is-active class.
*
* The link is only active if its path corresponds to the current path, the
* language of the linked path is equal to the current language, and if the
* query parameters of the link equal those of the current request, since the
* same request with different query parameters may yield a different page
* (e.g. pagers, exposed View filters).
*
* Does not discriminate based on element type, so allows you to set the
* is-active class on any element: a, li…
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.activeLinks = {
attach: function (context) {
// Start by finding all potentially active links.
var path = drupalSettings.path;
var queryString = JSON.stringify(path.currentQuery);
var querySelector = path.currentQuery ? "[data-drupal-link-query='" + queryString + "']" : ':not([data-drupal-link-query])';
var originalSelectors = ['[data-drupal-link-system-path="' + path.currentPath + '"]'];
var selectors;
// If this is the front page, we have to check for the <front> path as
// well.
if (path.isFront) {
originalSelectors.push('[data-drupal-link-system-path="<front>"]');
}
// Add language filtering.
selectors = [].concat(
// Links without any hreflang attributes (most of them).
originalSelectors.map(function (selector) { return selector + ':not([hreflang])'; }),
// Links with hreflang equals to the current language.
originalSelectors.map(function (selector) { return selector + '[hreflang="' + path.currentLanguage + '"]'; })
);
// Add query string selector for pagers, exposed filters.
selectors = selectors.map(function (current) { return current + querySelector; });
// Query the DOM.
var activeLinks = context.querySelectorAll(selectors.join(','));
var il = activeLinks.length;
for (var i = 0; i < il; i++) {
activeLinks[i].classList.add('is-active');
}
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
var activeLinks = context.querySelectorAll('[data-drupal-link-system-path].is-active');
var il = activeLinks.length;
for (var i = 0; i < il; i++) {
activeLinks[i].classList.remove('is-active');
}
}
}
};
})(Drupal, drupalSettings);
;
/**
* @file
* JavaScript API for the History module, with client-side caching.
*
* May only be loaded for authenticated users, with the History module enabled.
*/
(function ($, Drupal, drupalSettings, storage) {
'use strict';
var currentUserID = parseInt(drupalSettings.user.uid, 10);
// Any comment that is older than 30 days is automatically considered read,
// so for these we don't need to perform a request at all!
var thirtyDaysAgo = Math.round(new Date().getTime() / 1000) - 30 * 24 * 60 * 60;
// Use the data embedded in the page, if available.
var embeddedLastReadTimestamps = false;
if (drupalSettings.history && drupalSettings.history.lastReadTimestamps) {
embeddedLastReadTimestamps = drupalSettings.history.lastReadTimestamps;
}
/**
* @namespace
*/
Drupal.history = {
/**
* Fetch "last read" timestamps for the given nodes.
*
* @param {Array} nodeIDs
* An array of node IDs.
* @param {function} callback
* A callback that is called after the requested timestamps were fetched.
*/
fetchTimestamps: function (nodeIDs, callback) {
// Use the data embedded in the page, if available.
if (embeddedLastReadTimestamps) {
callback();
return;
}
$.ajax({
url: Drupal.url('history/get_node_read_timestamps'),
type: 'POST',
data: {'node_ids[]': nodeIDs},
dataType: 'json',
success: function (results) {
for (var nodeID in results) {
if (results.hasOwnProperty(nodeID)) {
storage.setItem('Drupal.history.' + currentUserID + '.' + nodeID, results[nodeID]);
}
}
callback();
}
});
},
/**
* Get the last read timestamp for the given node.
*
* @param {number|string} nodeID
* A node ID.
*
* @return {number}
* A UNIX timestamp.
*/
getLastRead: function (nodeID) {
// Use the data embedded in the page, if available.
if (embeddedLastReadTimestamps && embeddedLastReadTimestamps[nodeID]) {
return parseInt(embeddedLastReadTimestamps[nodeID], 10);
}
return parseInt(storage.getItem('Drupal.history.' + currentUserID + '.' + nodeID) || 0, 10);
},
/**
* Marks a node as read, store the last read timestamp client-side.
*
* @param {number|string} nodeID
* A node ID.
*/
markAsRead: function (nodeID) {
$.ajax({
url: Drupal.url('history/' + nodeID + '/read'),
type: 'POST',
dataType: 'json',
success: function (timestamp) {
// If the data is embedded in the page, don't store on the client
// side.
if (embeddedLastReadTimestamps && embeddedLastReadTimestamps[nodeID]) {
return;
}
storage.setItem('Drupal.history.' + currentUserID + '.' + nodeID, timestamp);
}
});
},
/**
* Determines whether a server check is necessary.
*
* Any content that is >30 days old never gets a "new" or "updated"
* indicator. Any content that was published before the oldest known reading
* also never gets a "new" or "updated" indicator, because it must've been
* read already.
*
* @param {number|string} nodeID
* A node ID.
* @param {number} contentTimestamp
* The time at which some content (e.g. a comment) was published.
*
* @return {bool}
* Whether a server check is necessary for the given node and its
* timestamp.
*/
needsServerCheck: function (nodeID, contentTimestamp) {
// First check if the content is older than 30 days, then we can bail
// early.
if (contentTimestamp < thirtyDaysAgo) {
return false;
}
// Use the data embedded in the page, if available.
if (embeddedLastReadTimestamps && embeddedLastReadTimestamps[nodeID]) {
return contentTimestamp > parseInt(embeddedLastReadTimestamps[nodeID], 10);
}
var minLastReadTimestamp = parseInt(storage.getItem('Drupal.history.' + currentUserID + '.' + nodeID) || 0, 10);
return contentTimestamp > minLastReadTimestamp;
}
};
})(jQuery, Drupal, drupalSettings, window.localStorage);
;
/**
* @file
* Marks the nodes listed in drupalSettings.history.nodesToMarkAsRead as read.
*
* Uses the History module JavaScript API.
*
* @see Drupal.history
*/
(function (window, Drupal, drupalSettings) {
'use strict';
// When the window's "load" event is triggered, mark all enumerated nodes as
// read. This still allows for Drupal behaviors (which are triggered on the
// "DOMContentReady" event) to add "new" and "updated" indicators.
window.addEventListener('load', function () {
if (drupalSettings.history && drupalSettings.history.nodesToMarkAsRead) {
Object.keys(drupalSettings.history.nodesToMarkAsRead).forEach(Drupal.history.markAsRead);
}
});
})(window, Drupal, drupalSettings);
;
/**
* @file
* Adds an HTML element and method to trigger audio UAs to read system messages.
*
* Use {@link Drupal.announce} to indicate to screen reader users that an
* element on the page has changed state. For instance, if clicking a link
* loads 10 more items into a list, one might announce the change like this.
*
* @example
* $('#search-list')
* .on('itemInsert', function (event, data) {
* // Insert the new items.
* $(data.container.el).append(data.items.el);
* // Announce the change to the page contents.
* Drupal.announce(Drupal.t('@count items added to @container',
* {'@count': data.items.length, '@container': data.container.title}
* ));
* });
*/
(function (Drupal, debounce) {
'use strict';
var liveElement;
var announcements = [];
/**
* Builds a div element with the aria-live attribute and add it to the DOM.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the behavior for drupalAnnouce.
*/
Drupal.behaviors.drupalAnnounce = {
attach: function (context) {
// Create only one aria-live element.
if (!liveElement) {
liveElement = document.createElement('div');
liveElement.id = 'drupal-live-announce';
liveElement.className = 'visually-hidden';
liveElement.setAttribute('aria-live', 'polite');
liveElement.setAttribute('aria-busy', 'false');
document.body.appendChild(liveElement);
}
}
};
/**
* Concatenates announcements to a single string; appends to the live region.
*/
function announce() {
var text = [];
var priority = 'polite';
var announcement;
// Create an array of announcement strings to be joined and appended to the
// aria live region.
var il = announcements.length;
for (var i = 0; i < il; i++) {
announcement = announcements.pop();
text.unshift(announcement.text);
// If any of the announcements has a priority of assertive then the group
// of joined announcements will have this priority.
if (announcement.priority === 'assertive') {
priority = 'assertive';
}
}
if (text.length) {
// Clear the liveElement so that repeated strings will be read.
liveElement.innerHTML = '';
// Set the busy state to true until the node changes are complete.
liveElement.setAttribute('aria-busy', 'true');
// Set the priority to assertive, or default to polite.
liveElement.setAttribute('aria-live', priority);
// Print the text to the live region. Text should be run through
// Drupal.t() before being passed to Drupal.announce().
liveElement.innerHTML = text.join('\n');
// The live text area is updated. Allow the AT to announce the text.
liveElement.setAttribute('aria-busy', 'false');
}
}
/**
* Triggers audio UAs to read the supplied text.
*
* The aria-live region will only read the text that currently populates its
* text node. Replacing text quickly in rapid calls to announce results in
* only the text from the most recent call to {@link Drupal.announce} being
* read. By wrapping the call to announce in a debounce function, we allow for
* time for multiple calls to {@link Drupal.announce} to queue up their
* messages. These messages are then joined and append to the aria-live region
* as one text node.
*
* @param {string} text
* A string to be read by the UA.
* @param {string} [priority='polite']
* A string to indicate the priority of the message. Can be either
* 'polite' or 'assertive'.
*
* @return {function}
* The return of the call to debounce.
*
* @see http://www.w3.org/WAI/PF/aria-practices/#liveprops
*/
Drupal.announce = function (text, priority) {
// Save the text and priority into a closure variable. Multiple simultaneous
// announcements will be concatenated and read in sequence.
announcements.push({
text: text,
priority: priority
});
// Immediately invoke the function that debounce returns. 200 ms is right at
// the cusp where humans notice a pause, so we will wait
// at most this much time before the set of queued announcements is read.
return (debounce(announce, 200)());
};
}(Drupal, Drupal.debounce));
;
window.matchMedia||(window.matchMedia=function(){"use strict";var e=window.styleMedia||window.media;if(!e){var t=document.createElement("style"),i=document.getElementsByTagName("script")[0],n=null;t.type="text/css";t.id="matchmediajs-test";i.parentNode.insertBefore(t,i);n="getComputedStyle"in window&&window.getComputedStyle(t,null)||t.currentStyle;e={matchMedium:function(e){var i="@media "+e+"{ #matchmediajs-test { width: 1px; } }";if(t.styleSheet){t.styleSheet.cssText=i}else{t.textContent=i}return n.width==="1px"}}}return function(t){return{matches:e.matchMedium(t||"all"),media:t||"all"}}}());
;
(function(){if(window.matchMedia&&window.matchMedia("all").addListener){return false}var e=window.matchMedia,i=e("only all").matches,n=false,t=0,a=[],r=function(i){clearTimeout(t);t=setTimeout(function(){for(var i=0,n=a.length;i<n;i++){var t=a[i].mql,r=a[i].listeners||[],o=e(t.media).matches;if(o!==t.matches){t.matches=o;for(var s=0,l=r.length;s<l;s++){r[s].call(window,t)}}}},30)};window.matchMedia=function(t){var o=e(t),s=[],l=0;o.addListener=function(e){if(!i){return}if(!n){n=true;window.addEventListener("resize",r,true)}if(l===0){l=a.push({mql:o,listeners:s})}s.push(e)};o.removeListener=function(e){for(var i=0,n=s.length;i<n;i++){if(s[i]===e){s.splice(i,1)}}};return o}})();
;
/**
* @file
* Builds a nested accordion widget.
*
* Invoke on an HTML list element with the jQuery plugin pattern.
*
* @example
* $('.toolbar-menu').drupalToolbarMenu();
*/
(function ($, Drupal, drupalSettings) {
'use strict';
/**
* Store the open menu tray.
*/
var activeItem = Drupal.url(drupalSettings.path.currentPath);
$.fn.drupalToolbarMenu = function () {
var ui = {
handleOpen: Drupal.t('Extend'),
handleClose: Drupal.t('Collapse')
};
/**
* Handle clicks from the disclosure button on an item with sub-items.
*
* @param {Object} event
* A jQuery Event object.
*/
function toggleClickHandler(event) {
var $toggle = $(event.target);
var $item = $toggle.closest('li');
// Toggle the list item.
toggleList($item);
// Close open sibling menus.
var $openItems = $item.siblings().filter('.open');
toggleList($openItems, false);
}
/**
* Handle clicks from a menu item link.
*
* @param {Object} event
* A jQuery Event object.
*/
function linkClickHandler(event) {
// If the toolbar is positioned fixed (and therefore hiding content
// underneath), then users expect clicks in the administration menu tray
// to take them to that destination but for the menu tray to be closed
// after clicking: otherwise the toolbar itself is obstructing the view
// of the destination they chose.
if (!Drupal.toolbar.models.toolbarModel.get('isFixed')) {
Drupal.toolbar.models.toolbarModel.set('activeTab', null);
}
// Stopping propagation to make sure that once a toolbar-box is clicked
// (the whitespace part), the page is not redirected anymore.
event.stopPropagation();
}
/**
* Toggle the open/close state of a list is a menu.
*
* @param {jQuery} $item
* The li item to be toggled.
*
* @param {Boolean} switcher
* A flag that forces toggleClass to add or a remove a class, rather than
* simply toggling its presence.
*/
function toggleList($item, switcher) {
var $toggle = $item.children('.toolbar-box').children('.toolbar-handle');
switcher = (typeof switcher !== 'undefined') ? switcher : !$item.hasClass('open');
// Toggle the item open state.
$item.toggleClass('open', switcher);
// Twist the toggle.
$toggle.toggleClass('open', switcher);
// Adjust the toggle text.
$toggle
.find('.action')
// Expand Structure, Collapse Structure.
.text((switcher) ? ui.handleClose : ui.handleOpen);
}
/**
* Add markup to the menu elements.
*
* Items with sub-elements have a list toggle attached to them. Menu item
* links and the corresponding list toggle are wrapped with in a div
* classed with .toolbar-box. The .toolbar-box div provides a positioning
* context for the item list toggle.
*
* @param {jQuery} $menu
* The root of the menu to be initialized.
*/
function initItems($menu) {
var options = {
class: 'toolbar-icon toolbar-handle',
action: ui.handleOpen,
text: ''
};
// Initialize items and their links.
$menu.find('li > a').wrap('<div class="toolbar-box">');
// Add a handle to each list item if it has a menu.
$menu.find('li').each(function (index, element) {
var $item = $(element);
if ($item.children('ul.toolbar-menu').length) {
var $box = $item.children('.toolbar-box');
options.text = Drupal.t('@label', {'@label': $box.find('a').text()});
$item.children('.toolbar-box')
.append(Drupal.theme('toolbarMenuItemToggle', options));
}
});
}
/**
* Adds a level class to each list based on its depth in the menu.
*
* This function is called recursively on each sub level of lists elements
* until the depth of the menu is exhausted.
*
* @param {jQuery} $lists
* A jQuery object of ul elements.
*
* @param {number} level
* The current level number to be assigned to the list elements.
*/
function markListLevels($lists, level) {
level = (!level) ? 1 : level;
var $lis = $lists.children('li').addClass('level-' + level);
$lists = $lis.children('ul');
if ($lists.length) {
markListLevels($lists, level + 1);
}
}
/**
* On page load, open the active menu item.
*
* Marks the trail of the active link in the menu back to the root of the
* menu with .menu-item--active-trail.
*
* @param {jQuery} $menu
* The root of the menu.
*/
function openActiveItem($menu) {
var pathItem = $menu.find('a[href="' + location.pathname + '"]');
if (pathItem.length && !activeItem) {
activeItem = location.pathname;
}
if (activeItem) {
var $activeItem = $menu.find('a[href="' + activeItem + '"]').addClass('menu-item--active');
var $activeTrail = $activeItem.parentsUntil('.root', 'li').addClass('menu-item--active-trail');
toggleList($activeTrail, true);
}
}
// Return the jQuery object.
return this.each(function (selector) {
var $menu = $(this).once('toolbar-menu');
if ($menu.length) {
// Bind event handlers.
$menu
.on('click.toolbar', '.toolbar-box', toggleClickHandler)
.on('click.toolbar', '.toolbar-box a', linkClickHandler);
$menu.addClass('root');
initItems($menu);
markListLevels($menu);
// Restore previous and active states.
openActiveItem($menu);
}
});
};
/**
* A toggle is an interactive element often bound to a click handler.
*
* @param {object} options
* Options for the button.
* @param {string} options.class
* Class to set on the button.
* @param {string} options.action
* Action for the button.
* @param {string} options.text
* Used as label for the button.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.toolbarMenuItemToggle = function (options) {
return '<button class="' + options['class'] + '"><span class="action">' + options.action + '</span><span class="label">' + options.text + '</span></button>';
};
}(jQuery, Drupal, drupalSettings));
;
/**
* @file
* Defines the behavior of the Drupal administration toolbar.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
// Merge run-time settings with the defaults.
var options = $.extend(
{
breakpoints: {
'toolbar.narrow': '',
'toolbar.standard': '',
'toolbar.wide': ''
}
},
drupalSettings.toolbar,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
horizontal: Drupal.t('Horizontal orientation'),
vertical: Drupal.t('Vertical orientation')
}
}
);
/**
* Registers tabs with the toolbar.
*
* The Drupal toolbar allows modules to register top-level tabs. These may
* point directly to a resource or toggle the visibility of a tray.
*
* Modules register tabs with hook_toolbar().
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the toolbar rendering functionality to the toolbar element.
*/
Drupal.behaviors.toolbar = {
attach: function (context) {
// Verify that the user agent understands media queries. Complex admin
// toolbar layouts require media query support.
if (!window.matchMedia('only screen').matches) {
return;
}
// Process the administrative toolbar.
$(context).find('#toolbar-administration').once('toolbar').each(function () {
// Establish the toolbar models and views.
var model = Drupal.toolbar.models.toolbarModel = new Drupal.toolbar.ToolbarModel({
locked: JSON.parse(localStorage.getItem('Drupal.toolbar.trayVerticalLocked')) || false,
activeTab: document.getElementById(JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID')))
});
Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView({
el: this,
model: model
});
// Render collapsible menus.
var menuModel = Drupal.toolbar.models.menuModel = new Drupal.toolbar.MenuModel();
Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView({
el: $(this).find('.toolbar-menu-administration').get(0),
model: menuModel,
strings: options.strings
});
// Handle the resolution of Drupal.toolbar.setSubtrees.
// This is handled with a deferred so that the function may be invoked
// asynchronously.
Drupal.toolbar.setSubtrees.done(function (subtrees) {
menuModel.set('subtrees', subtrees);
var theme = drupalSettings.ajaxPageState.theme;
localStorage.setItem('Drupal.toolbar.subtrees.' + theme, JSON.stringify(subtrees));
// Indicate on the toolbarModel that subtrees are now loaded.
model.set('areSubtreesLoaded', true);
});
// Attach a listener to the configured media query breakpoints.
for (var label in options.breakpoints) {
if (options.breakpoints.hasOwnProperty(label)) {
var mq = options.breakpoints[label];
var mql = Drupal.toolbar.mql[label] = window.matchMedia(mq);
// Curry the model and the label of the media query breakpoint to
// the mediaQueryChangeHandler function.
mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label));
// Fire the mediaQueryChangeHandler for each configured breakpoint
// so that they process once.
Drupal.toolbar.mediaQueryChangeHandler.call(null, model, label, mql);
}
}
// Trigger an initial attempt to load menu subitems. This first attempt
// is made after the media query handlers have had an opportunity to
// process. The toolbar starts in the vertical orientation by default,
// unless the viewport is wide enough to accommodate a horizontal
// orientation. Thus we give the Toolbar a chance to determine if it
// should be set to horizontal orientation before attempting to load
// menu subtrees.
Drupal.toolbar.views.toolbarVisualView.loadSubtrees();
$(document)
// Update the model when the viewport offset changes.
.on('drupalViewportOffsetChange.toolbar', function (event, offsets) {
model.set('offsets', offsets);
});
// Broadcast model changes to other modules.
model
.on('change:orientation', function (model, orientation) {
$(document).trigger('drupalToolbarOrientationChange', orientation);
})
.on('change:activeTab', function (model, tab) {
$(document).trigger('drupalToolbarTabChange', tab);
})
.on('change:activeTray', function (model, tray) {
$(document).trigger('drupalToolbarTrayChange', tray);
});
// If the toolbar's orientation is horizontal and no active tab is
// defined then show the tray of the first toolbar tab by default (but
// not the first 'Home' toolbar tab).
if (Drupal.toolbar.models.toolbarModel.get('orientation') === 'horizontal' && Drupal.toolbar.models.toolbarModel.get('activeTab') === null) {
Drupal.toolbar.models.toolbarModel.set({
activeTab: $('.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a').get(0)
});
}
});
}
};
/**
* Toolbar methods of Backbone objects.
*
* @namespace
*/
Drupal.toolbar = {
/**
* A hash of View instances.
*
* @type {object.<string, Backbone.View>}
*/
views: {},
/**
* A hash of Model instances.
*
* @type {object.<string, Backbone.Model>}
*/
models: {},
/**
* A hash of MediaQueryList objects tracked by the toolbar.
*
* @type {object.<string, object>}
*/
mql: {},
/**
* Accepts a list of subtree menu elements.
*
* A deferred object that is resolved by an inlined JavaScript callback.
*
* @type {jQuery.Deferred}
*
* @see toolbar_subtrees_jsonp().
*/
setSubtrees: new $.Deferred(),
/**
* Respond to configured narrow media query changes.
*
* @param {Drupal.toolbar.ToolbarModel} model
* A toolbar model
* @param {string} label
* Media query label.
* @param {object} mql
* A MediaQueryList object.
*/
mediaQueryChangeHandler: function (model, label, mql) {
switch (label) {
case 'toolbar.narrow':
model.set({
isOriented: mql.matches,
isTrayToggleVisible: false
});
// If the toolbar doesn't have an explicit orientation yet, or if the
// narrow media query doesn't match then set the orientation to
// vertical.
if (!mql.matches || !model.get('orientation')) {
model.set({orientation: 'vertical'}, {validate: true});
}
break;
case 'toolbar.standard':
model.set({
isFixed: mql.matches
});
break;
case 'toolbar.wide':
model.set({
orientation: ((mql.matches) ? 'horizontal' : 'vertical')
}, {validate: true});
// The tray orientation toggle visibility does not need to be
// validated.
model.set({
isTrayToggleVisible: mql.matches
});
break;
default:
break;
}
}
};
/**
* A toggle is an interactive element often bound to a click handler.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.toolbarOrientationToggle = function () {
return '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' +
'<button class="toolbar-icon" type="button"></button>' +
'</div></div>';
};
/**
* Ajax command to set the toolbar subtrees.
*
* @param {Drupal.Ajax} ajax
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* JSON response from the Ajax request.
* @param {number} [status]
* XMLHttpRequest status.
*/
Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (ajax, response, status) {
Drupal.toolbar.setSubtrees.resolve(response.subtrees);
};
}(jQuery, Drupal, drupalSettings));
;
/**
* @file
* A Backbone Model for collapsible menus.
*/
(function (Backbone, Drupal) {
'use strict';
/**
* Backbone Model for collapsible menus.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.toolbar.MenuModel = Backbone.Model.extend(/** @lends Drupal.toolbar.MenuModel# */{
/**
* @type {object}
*
* @prop {object} subtrees
*/
defaults: /** @lends Drupal.toolbar.MenuModel# */{
/**
* @type {object}
*/
subtrees: {}
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the toolbar.
*/
(function (Backbone, Drupal) {
'use strict';
/**
* Backbone model for the toolbar.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.toolbar.ToolbarModel = Backbone.Model.extend(/** @lends Drupal.toolbar.ToolbarModel# */{
/**
* @type {object}
*
* @prop activeTab
* @prop activeTray
* @prop isOriented
* @prop isFixed
* @prop areSubtreesLoaded
* @prop isViewportOverflowConstrained
* @prop orientation
* @prop locked
* @prop isTrayToggleVisible
* @prop height
* @prop offsets
*/
defaults: /** @lends Drupal.toolbar.ToolbarModel# */{
/**
* The active toolbar tab. All other tabs should be inactive under
* normal circumstances. It will remain active across page loads. The
* active item is stored as an ID selector e.g. '#toolbar-item--1'.
*
* @type {string}
*/
activeTab: null,
/**
* Represents whether a tray is open or not. Stored as an ID selector e.g.
* '#toolbar-item--1-tray'.
*
* @type {string}
*/
activeTray: null,
/**
* Indicates whether the toolbar is displayed in an oriented fashion,
* either horizontal or vertical.
*
* @type {bool}
*/
isOriented: false,
/**
* Indicates whether the toolbar is positioned absolute (false) or fixed
* (true).
*
* @type {bool}
*/
isFixed: false,
/**
* Menu subtrees are loaded through an AJAX request only when the Toolbar
* is set to a vertical orientation.
*
* @type {bool}
*/
areSubtreesLoaded: false,
/**
* If the viewport overflow becomes constrained, isFixed must be true so
* that elements in the trays aren't lost off-screen and impossible to
* get to.
*
* @type {bool}
*/
isViewportOverflowConstrained: false,
/**
* The orientation of the active tray.
*
* @type {string}
*/
orientation: 'vertical',
/**
* A tray is locked if a user toggled it to vertical. Otherwise a tray
* will switch between vertical and horizontal orientation based on the
* configured breakpoints. The locked state will be maintained across page
* loads.
*
* @type {bool}
*/
locked: false,
/**
* Indicates whether the tray orientation toggle is visible.
*
* @type {bool}
*/
isTrayToggleVisible: false,
/**
* The height of the toolbar.
*
* @type {number}
*/
height: null,
/**
* The current viewport offsets determined by {@link Drupal.displace}. The
* offsets suggest how a module might position is components relative to
* the viewport.
*
* @type {object}
*
* @prop {number} top
* @prop {number} right
* @prop {number} bottom
* @prop {number} left
*/
offsets: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
},
/**
* @inheritdoc
*
* @param {object} attributes
* Attributes for the toolbar.
* @param {object} options
* Options for the toolbar.
*
* @return {string|undefined}
* Returns an error message if validation failed.
*/
validate: function (attributes, options) {
// Prevent the orientation being set to horizontal if it is locked, unless
// override has not been passed as an option.
if (attributes.orientation === 'horizontal' && this.get('locked') && !options.override) {
return Drupal.t('The toolbar cannot be set to a horizontal orientation when it is locked.');
}
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone view for the body element.
*/
(function ($, Drupal, Backbone) {
'use strict';
Drupal.toolbar.BodyVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.BodyVisualView# */{
/**
* Adjusts the body element with the toolbar position and dimension changes.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:orientation change:offsets change:activeTray change:isOriented change:isFixed change:isViewportOverflowConstrained', this.render);
},
/**
* @inheritdoc
*/
render: function () {
var $body = $('body');
var orientation = this.model.get('orientation');
var isOriented = this.model.get('isOriented');
var isViewportOverflowConstrained = this.model.get('isViewportOverflowConstrained');
$body
// We are using JavaScript to control media-query handling for two
// reasons: (1) Using JavaScript let's us leverage the breakpoint
// configurations and (2) the CSS is really complex if we try to hide
// some styling from browsers that don't understand CSS media queries.
// If we drive the CSS from classes added through JavaScript,
// then the CSS becomes simpler and more robust.
.toggleClass('toolbar-vertical', (orientation === 'vertical'))
.toggleClass('toolbar-horizontal', (isOriented && orientation === 'horizontal'))
// When the toolbar is fixed, it will not scroll with page scrolling.
.toggleClass('toolbar-fixed', (isViewportOverflowConstrained || this.model.get('isFixed')))
// Toggle the toolbar-tray-open class on the body element. The class is
// applied when a toolbar tray is active. Padding might be applied to
// the body element to prevent the tray from overlapping content.
.toggleClass('toolbar-tray-open', !!this.model.get('activeTray'))
// Apply padding to the top of the body to offset the placement of the
// toolbar bar element.
.css('padding-top', this.model.get('offsets').top);
}
});
}(jQuery, Drupal, Backbone));
;
/**
* @file
* A Backbone view for the collapsible menus.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.toolbar.MenuVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.MenuVisualView# */{
/**
* Backbone View for collapsible menus.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:subtrees', this.render);
},
/**
* @inheritdoc
*/
render: function () {
var subtrees = this.model.get('subtrees');
// Add subtrees.
for (var id in subtrees) {
if (subtrees.hasOwnProperty(id)) {
this.$el
.find('#toolbar-link-' + id)
.once('toolbar-subtrees')
.after(subtrees[id]);
}
}
// Render the main menu as a nested, collapsible accordion.
if ('drupalToolbarMenu' in $.fn) {
this.$el
.children('.toolbar-menu')
.drupalToolbarMenu();
}
}
});
}(jQuery, Backbone, Drupal));
;
/**
* @file
* A Backbone view for the aural feedback of the toolbar.
*/
(function (Backbone, Drupal) {
'use strict';
Drupal.toolbar.ToolbarAuralView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarAuralView# */{
/**
* Backbone view for the aural feedback of the toolbar.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
* @param {object} options.strings
* Various strings to use in the view.
*/
initialize: function (options) {
this.strings = options.strings;
this.listenTo(this.model, 'change:orientation', this.onOrientationChange);
this.listenTo(this.model, 'change:activeTray', this.onActiveTrayChange);
},
/**
* Announces an orientation change.
*
* @param {Drupal.toolbar.ToolbarModel} model
* The toolbar model in question.
* @param {string} orientation
* The new value of the orientation attribute in the model.
*/
onOrientationChange: function (model, orientation) {
Drupal.announce(Drupal.t('Tray orientation changed to @orientation.', {
'@orientation': orientation
}));
},
/**
* Announces a changed active tray.
*
* @param {Drupal.toolbar.ToolbarModel} model
* The toolbar model in question.
* @param {HTMLElement} tray
* The new value of the tray attribute in the model.
*/
onActiveTrayChange: function (model, tray) {
var relevantTray = (tray === null) ? model.previous('activeTray') : tray;
var action = (tray === null) ? Drupal.t('closed') : Drupal.t('opened');
var trayNameElement = relevantTray.querySelector('.toolbar-tray-name');
var text;
if (trayNameElement !== null) {
text = Drupal.t('Tray "@tray" @action.', {
'@tray': trayNameElement.textContent, '@action': action
});
}
else {
text = Drupal.t('Tray @action.', {'@action': action});
}
Drupal.announce(text);
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone view for the toolbar element. Listens to mouse & touch.
*/
(function ($, Drupal, drupalSettings, Backbone) {
'use strict';
Drupal.toolbar.ToolbarVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarVisualView# */{
/**
* Event map for the `ToolbarVisualView`.
*
* @return {object}
* A map of events.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
return {
'click .toolbar-bar .toolbar-tab .trigger': 'onTabClick',
'click .toolbar-toggle-orientation button': 'onOrientationToggleClick',
'touchend .toolbar-bar .toolbar-tab .trigger': touchEndToClick,
'touchend .toolbar-toggle-orientation button': touchEndToClick
};
},
/**
* Backbone view for the toolbar element. Listens to mouse & touch.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view object.
* @param {object} options.strings
* Various strings to use in the view.
*/
initialize: function (options) {
this.strings = options.strings;
this.listenTo(this.model, 'change:activeTab change:orientation change:isOriented change:isTrayToggleVisible', this.render);
this.listenTo(this.model, 'change:mqMatches', this.onMediaQueryChange);
this.listenTo(this.model, 'change:offsets', this.adjustPlacement);
// Add the tray orientation toggles.
this.$el
.find('.toolbar-tray .toolbar-lining')
.append(Drupal.theme('toolbarOrientationToggle'));
// Trigger an activeTab change so that listening scripts can respond on
// page load. This will call render.
this.model.trigger('change:activeTab');
},
/**
* @inheritdoc
*
* @return {Drupal.toolbar.ToolbarVisualView}
* The `ToolbarVisualView` instance.
*/
render: function () {
this.updateTabs();
this.updateTrayOrientation();
this.updateBarAttributes();
// Load the subtrees if the orientation of the toolbar is changed to
// vertical. This condition responds to the case that the toolbar switches
// from horizontal to vertical orientation. The toolbar starts in a
// vertical orientation by default and then switches to horizontal during
// initialization if the media query conditions are met. Simply checking
// that the orientation is vertical here would result in the subtrees
// always being loaded, even when the toolbar initialization ultimately
// results in a horizontal orientation.
//
// @see Drupal.behaviors.toolbar.attach() where admin menu subtrees
// loading is invoked during initialization after media query conditions
// have been processed.
if (this.model.changed.orientation === 'vertical' || this.model.changed.activeTab) {
this.loadSubtrees();
}
// Trigger a recalculation of viewport displacing elements. Use setTimeout
// to ensure this recalculation happens after changes to visual elements
// have processed.
window.setTimeout(function () {
Drupal.displace(true);
}, 0);
return this;
},
/**
* Responds to a toolbar tab click.
*
* @param {jQuery.Event} event
* The event triggered.
*/
onTabClick: function (event) {
// If this tab has a tray associated with it, it is considered an
// activatable tab.
if (event.target.hasAttribute('data-toolbar-tray')) {
var activeTab = this.model.get('activeTab');
var clickedTab = event.target;
// Set the event target as the active item if it is not already.
this.model.set('activeTab', (!activeTab || clickedTab !== activeTab) ? clickedTab : null);
event.preventDefault();
event.stopPropagation();
}
},
/**
* Toggles the orientation of a toolbar tray.
*
* @param {jQuery.Event} event
* The event triggered.
*/
onOrientationToggleClick: function (event) {
var orientation = this.model.get('orientation');
// Determine the toggle-to orientation.
var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical';
var locked = antiOrientation === 'vertical';
// Remember the locked state.
if (locked) {
localStorage.setItem('Drupal.toolbar.trayVerticalLocked', 'true');
}
else {
localStorage.removeItem('Drupal.toolbar.trayVerticalLocked');
}
// Update the model.
this.model.set({
locked: locked,
orientation: antiOrientation
}, {
validate: true,
override: true
});
event.preventDefault();
event.stopPropagation();
},
/**
* Updates the display of the tabs: toggles a tab and the associated tray.
*/
updateTabs: function () {
var $tab = $(this.model.get('activeTab'));
// Deactivate the previous tab.
$(this.model.previous('activeTab'))
.removeClass('is-active')
.prop('aria-pressed', false);
// Deactivate the previous tray.
$(this.model.previous('activeTray'))
.removeClass('is-active');
// Activate the selected tab.
if ($tab.length > 0) {
$tab
.addClass('is-active')
// Mark the tab as pressed.
.prop('aria-pressed', true);
var name = $tab.attr('data-toolbar-tray');
// Store the active tab name or remove the setting.
var id = $tab.get(0).id;
if (id) {
localStorage.setItem('Drupal.toolbar.activeTabID', JSON.stringify(id));
}
// Activate the associated tray.
var $tray = this.$el.find('[data-toolbar-tray="' + name + '"].toolbar-tray');
if ($tray.length) {
$tray.addClass('is-active');
this.model.set('activeTray', $tray.get(0));
}
else {
// There is no active tray.
this.model.set('activeTray', null);
}
}
else {
// There is no active tray.
this.model.set('activeTray', null);
localStorage.removeItem('Drupal.toolbar.activeTabID');
}
},
/**
* Update the attributes of the toolbar bar element.
*/
updateBarAttributes: function () {
var isOriented = this.model.get('isOriented');
if (isOriented) {
this.$el.find('.toolbar-bar').attr('data-offset-top', '');
}
else {
this.$el.find('.toolbar-bar').removeAttr('data-offset-top');
}
// Toggle between a basic vertical view and a more sophisticated
// horizontal and vertical display of the toolbar bar and trays.
this.$el.toggleClass('toolbar-oriented', isOriented);
},
/**
* Updates the orientation of the active tray if necessary.
*/
updateTrayOrientation: function () {
var orientation = this.model.get('orientation');
// The antiOrientation is used to render the view of action buttons like
// the tray orientation toggle.
var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical';
// Update the orientation of the trays.
var $trays = this.$el.find('.toolbar-tray')
.removeClass('toolbar-tray-horizontal toolbar-tray-vertical')
.addClass('toolbar-tray-' + orientation);
// Update the tray orientation toggle button.
var iconClass = 'toolbar-icon-toggle-' + orientation;
var iconAntiClass = 'toolbar-icon-toggle-' + antiOrientation;
var $orientationToggle = this.$el.find('.toolbar-toggle-orientation')
.toggle(this.model.get('isTrayToggleVisible'));
$orientationToggle.find('button')
.val(antiOrientation)
.attr('title', this.strings[antiOrientation])
.text(this.strings[antiOrientation])
.removeClass(iconClass)
.addClass(iconAntiClass);
// Update data offset attributes for the trays.
var dir = document.documentElement.dir;
var edge = (dir === 'rtl') ? 'right' : 'left';
// Remove data-offset attributes from the trays so they can be refreshed.
$trays.removeAttr('data-offset-left data-offset-right data-offset-top');
// If an active vertical tray exists, mark it as an offset element.
$trays.filter('.toolbar-tray-vertical.is-active').attr('data-offset-' + edge, '');
// If an active horizontal tray exists, mark it as an offset element.
$trays.filter('.toolbar-tray-horizontal.is-active').attr('data-offset-top', '');
},
/**
* Sets the tops of the trays so that they align with the bottom of the bar.
*/
adjustPlacement: function () {
var $trays = this.$el.find('.toolbar-tray');
if (!this.model.get('isOriented')) {
$trays.css('margin-top', 0);
$trays.removeClass('toolbar-tray-horizontal').addClass('toolbar-tray-vertical');
}
else {
// The toolbar container is invisible. Its placement is used to
// determine the container for the trays.
$trays.css('margin-top', this.$el.find('.toolbar-bar').outerHeight());
}
},
/**
* Calls the endpoint URI that builds an AJAX command with the rendered
* subtrees.
*
* The rendered admin menu subtrees HTML is cached on the client in
* localStorage until the cache of the admin menu subtrees on the server-
* side is invalidated. The subtreesHash is stored in localStorage as well
* and compared to the subtreesHash in drupalSettings to determine when the
* admin menu subtrees cache has been invalidated.
*/
loadSubtrees: function () {
var $activeTab = $(this.model.get('activeTab'));
var orientation = this.model.get('orientation');
// Only load and render the admin menu subtrees if:
// (1) They have not been loaded yet.
// (2) The active tab is the administration menu tab, indicated by the
// presence of the data-drupal-subtrees attribute.
// (3) The orientation of the tray is vertical.
if (!this.model.get('areSubtreesLoaded') && typeof $activeTab.data('drupal-subtrees') !== 'undefined' && orientation === 'vertical') {
var subtreesHash = drupalSettings.toolbar.subtreesHash;
var theme = drupalSettings.ajaxPageState.theme;
var endpoint = Drupal.url('toolbar/subtrees/' + subtreesHash);
var cachedSubtreesHash = localStorage.getItem('Drupal.toolbar.subtreesHash.' + theme);
var cachedSubtrees = JSON.parse(localStorage.getItem('Drupal.toolbar.subtrees.' + theme));
var isVertical = this.model.get('orientation') === 'vertical';
// If we have the subtrees in localStorage and the subtree hash has not
// changed, then use the cached data.
if (isVertical && subtreesHash === cachedSubtreesHash && cachedSubtrees) {
Drupal.toolbar.setSubtrees.resolve(cachedSubtrees);
}
// Only make the call to get the subtrees if the orientation of the
// toolbar is vertical.
else if (isVertical) {
// Remove the cached menu information.
localStorage.removeItem('Drupal.toolbar.subtreesHash.' + theme);
localStorage.removeItem('Drupal.toolbar.subtrees.' + theme);
// The AJAX response's command will trigger the resolve method of the
// Drupal.toolbar.setSubtrees Promise.
Drupal.ajax({url: endpoint}).execute();
// Cache the hash for the subtrees locally.
localStorage.setItem('Drupal.toolbar.subtreesHash.' + theme, subtreesHash);
}
}
}
});
}(jQuery, Drupal, drupalSettings, Backbone));
;
/* jQuery Foundation Joyride Plugin 2.1 | Copyright 2012, ZURB | www.opensource.org/licenses/mit-license.php */
(function(e,t,n){"use strict";var r={version:"2.0.3",tipLocation:"bottom",nubPosition:"auto",scroll:!0,scrollSpeed:300,timer:0,autoStart:!1,startTimerOnClick:!0,startOffset:0,nextButton:!0,tipAnimation:"fade",pauseAfter:[],tipAnimationFadeSpeed:300,cookieMonster:!1,cookieName:"joyride",cookieDomain:!1,cookiePath:!1,localStorage:!1,localStorageKey:"joyride",tipContainer:"body",modal:!1,expose:!1,postExposeCallback:e.noop,preRideCallback:e.noop,postRideCallback:e.noop,preStepCallback:e.noop,postStepCallback:e.noop,template:{link:'<a href="#close" class="joyride-close-tip">X</a>',timer:'<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>',tip:'<div class="joyride-tip-guide"><span class="joyride-nub"></span></div>',wrapper:'<div class="joyride-content-wrapper" role="dialog"></div>',button:'<a href="#" class="joyride-next-tip"></a>',modal:'<div class="joyride-modal-bg"></div>',expose:'<div class="joyride-expose-wrapper"></div>',exposeCover:'<div class="joyride-expose-cover"></div>'}},i=i||!1,s={},o={init:function(n){return this.each(function(){e.isEmptyObject(s)?(s=e.extend(!0,r,n),s.document=t.document,s.$document=e(s.document),s.$window=e(t),s.$content_el=e(this),s.$body=e(s.tipContainer),s.body_offset=e(s.tipContainer).position(),s.$tip_content=e("> li",s.$content_el),s.paused=!1,s.attempts=0,s.tipLocationPatterns={top:["bottom"],bottom:[],left:["right","top","bottom"],right:["left","top","bottom"]},o.jquery_check(),e.isFunction(e.cookie)||(s.cookieMonster=!1),(!s.cookieMonster||!e.cookie(s.cookieName))&&(!s.localStorage||!o.support_localstorage()||!localStorage.getItem(s.localStorageKey))&&(s.$tip_content.each(function(t){o.create({$li:e(this),index:t})}),s.autoStart&&(!s.startTimerOnClick&&s.timer>0?(o.show("init"),o.startTimer()):o.show("init"))),s.$document.on("click.joyride",".joyride-next-tip, .joyride-modal-bg",function(e){e.preventDefault(),s.$li.next().length<1?o.end():s.timer>0?(clearTimeout(s.automate),o.hide(),o.show(),o.startTimer()):(o.hide(),o.show())}),s.$document.on("click.joyride",".joyride-close-tip",function(e){e.preventDefault(),o.end()}),s.$window.bind("resize.joyride",function(t){if(s.$li){if(s.exposed&&s.exposed.length>0){var n=e(s.exposed);n.each(function(){var t=e(this);o.un_expose(t),o.expose(t)})}o.is_phone()?o.pos_phone():o.pos_default()}})):o.restart()})},resume:function(){o.set_li(),o.show()},nextTip:function(){s.$li.next().length<1?o.end():s.timer>0?(clearTimeout(s.automate),o.hide(),o.show(),o.startTimer()):(o.hide(),o.show())},tip_template:function(t){var n,r,i;return t.tip_class=t.tip_class||"",n=e(s.template.tip).addClass(t.tip_class),r=e.trim(e(t.li).html())+o.button_text(t.button_text)+s.template.link+o.timer_instance(t.index),i=e(s.template.wrapper),t.li.attr("data-aria-labelledby")&&i.attr("aria-labelledby",t.li.attr("data-aria-labelledby")),t.li.attr("data-aria-describedby")&&i.attr("aria-describedby",t.li.attr("data-aria-describedby")),n.append(i),n.first().attr("data-index",t.index),e(".joyride-content-wrapper",n).append(r),n[0]},timer_instance:function(t){var n;return t===0&&s.startTimerOnClick&&s.timer>0||s.timer===0?n="":n=o.outerHTML(e(s.template.timer)[0]),n},button_text:function(t){return s.nextButton?(t=e.trim(t)||"Next",t=o.outerHTML(e(s.template.button).append(t)[0])):t="",t},create:function(t){var n=t.$li.attr("data-button")||t.$li.attr("data-text"),r=t.$li.attr("class"),i=e(o.tip_template({tip_class:r,index:t.index,button_text:n,li:t.$li}));e(s.tipContainer).append(i)},show:function(t){var r={},i,u=[],a=0,f,l=null;if(s.$li===n||e.inArray(s.$li.index(),s.pauseAfter)===-1){s.paused?s.paused=!1:o.set_li(t),s.attempts=0;if(s.$li.length&&s.$target.length>0){t&&(s.preRideCallback(s.$li.index(),s.$next_tip),s.modal&&o.show_modal()),s.preStepCallback(s.$li.index(),s.$next_tip),u=(s.$li.data("options")||":").split(";"),a=u.length;for(i=a-1;i>=0;i--)f=u[i].split(":"),f.length===2&&(r[e.trim(f[0])]=e.trim(f[1]));s.tipSettings=e.extend({},s,r),s.tipSettings.tipLocationPattern=s.tipLocationPatterns[s.tipSettings.tipLocation],s.modal&&s.expose&&o.expose(),!/body/i.test(s.$target.selector)&&s.scroll&&o.scroll_to(),o.is_phone()?o.pos_phone(!0):o.pos_default(!0),l=e(".joyride-timer-indicator",s.$next_tip),/pop/i.test(s.tipAnimation)?(l.outerWidth(0),s.timer>0?(s.$next_tip.show(),l.animate({width:e(".joyride-timer-indicator-wrap",s.$next_tip).outerWidth()},s.timer)):s.$next_tip.show()):/fade/i.test(s.tipAnimation)&&(l.outerWidth(0),s.timer>0?(s.$next_tip.fadeIn(s.tipAnimationFadeSpeed),s.$next_tip.show(),l.animate({width:e(".joyride-timer-indicator-wrap",s.$next_tip).outerWidth()},s.timer)):s.$next_tip.fadeIn(s.tipAnimationFadeSpeed)),s.$current_tip=s.$next_tip,e(".joyride-next-tip",s.$current_tip).focus(),o.tabbable(s.$current_tip)}else s.$li&&s.$target.length<1?o.show():o.end()}else s.paused=!0},is_phone:function(){return i?i.mq("only screen and (max-width: 767px)"):s.$window.width()<767?!0:!1},support_localstorage:function(){return i?i.localstorage:!!t.localStorage},hide:function(){s.modal&&s.expose&&o.un_expose(),s.modal||e(".joyride-modal-bg").hide(),s.$current_tip.hide(),s.postStepCallback(s.$li.index(),s.$current_tip)},set_li:function(e){e?(s.$li=s.$tip_content.eq(s.startOffset),o.set_next_tip(),s.$current_tip=s.$next_tip):(s.$li=s.$li.next(),o.set_next_tip()),o.set_target()},set_next_tip:function(){s.$next_tip=e(".joyride-tip-guide[data-index="+s.$li.index()+"]")},set_target:function(){var t=s.$li.attr("data-class"),n=s.$li.attr("data-id"),r=function(){return n?e(s.document.getElementById(n)):t?e("."+t).filter(":visible").first():e("body")};s.$target=r()},scroll_to:function(){var t,n;t=s.$window.height()/2,n=Math.ceil(s.$target.offset().top-t+s.$next_tip.outerHeight()),e("html, body").stop().animate({scrollTop:n},s.scrollSpeed)},paused:function(){return e.inArray(s.$li.index()+1,s.pauseAfter)===-1?!0:!1},destroy:function(){e.isEmptyObject(s)||s.$document.off(".joyride"),e(t).off(".joyride"),e(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off(".joyride"),e(".joyride-tip-guide, .joyride-modal-bg").remove(),clearTimeout(s.automate),s={}},restart:function(){s.autoStart?(o.hide(),s.$li=n,o.show("init")):(!s.startTimerOnClick&&s.timer>0?(o.show("init"),o.startTimer()):o.show("init"),s.autoStart=!0)},pos_default:function(t){var n=Math.ceil(s.$window.height()/2),r=s.$next_tip.offset(),i=e(".joyride-nub",s.$next_tip),u=Math.ceil(i.outerWidth()/2),a=Math.ceil(i.outerHeight()/2),f=t||!1;f&&(s.$next_tip.css("visibility","hidden"),s.$next_tip.show());if(!/body/i.test(s.$target.selector)){var l=s.tipSettings.tipAdjustmentY?parseInt(s.tipSettings.tipAdjustmentY):0,c=s.tipSettings.tipAdjustmentX?parseInt(s.tipSettings.tipAdjustmentX):0;o.bottom()?(s.$next_tip.css({top:s.$target.offset().top+a+s.$target.outerHeight()+l,left:s.$target.offset().left+c}),/right/i.test(s.tipSettings.nubPosition)&&s.$next_tip.css("left",s.$target.offset().left-s.$next_tip.outerWidth()+s.$target.outerWidth()),o.nub_position(i,s.tipSettings.nubPosition,"top")):o.top()?(s.$next_tip.css({top:s.$target.offset().top-s.$next_tip.outerHeight()-a+l,left:s.$target.offset().left+c}),o.nub_position(i,s.tipSettings.nubPosition,"bottom")):o.right()?(s.$next_tip.css({top:s.$target.offset().top+l,left:s.$target.outerWidth()+s.$target.offset().left+u+c}),o.nub_position(i,s.tipSettings.nubPosition,"left")):o.left()&&(s.$next_tip.css({top:s.$target.offset().top+l,left:s.$target.offset().left-s.$next_tip.outerWidth()-u+c}),o.nub_position(i,s.tipSettings.nubPosition,"right")),!o.visible(o.corners(s.$next_tip))&&s.attempts<s.tipSettings.tipLocationPattern.length&&(i.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),s.tipSettings.tipLocation=s.tipSettings.tipLocationPattern[s.attempts],s.attempts++,o.pos_default(!0))}else s.$li.length&&o.pos_modal(i);f&&(s.$next_tip.hide(),s.$next_tip.css("visibility","visible"))},pos_phone:function(t){var n=s.$next_tip.outerHeight(),r=s.$next_tip.offset(),i=s.$target.outerHeight(),u=e(".joyride-nub",s.$next_tip),a=Math.ceil(u.outerHeight()/2),f=t||!1;u.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),f&&(s.$next_tip.css("visibility","hidden"),s.$next_tip.show()),/body/i.test(s.$target.selector)?s.$li.length&&o.pos_modal(u):o.top()?(s.$next_tip.offset({top:s.$target.offset().top-n-a}),u.addClass("bottom")):(s.$next_tip.offset({top:s.$target.offset().top+i+a}),u.addClass("top")),f&&(s.$next_tip.hide(),s.$next_tip.css("visibility","visible"))},pos_modal:function(e){o.center(),e.hide(),o.show_modal()},show_modal:function(){e(".joyride-modal-bg").length<1&&e("body").append(s.template.modal).show(),/pop/i.test(s.tipAnimation)?e(".joyride-modal-bg").show():e(".joyride-modal-bg").fadeIn(s.tipAnimationFadeSpeed)},expose:function(){var n,r,i,u,a="expose-"+Math.floor(Math.random()*1e4);if(arguments.length>0&&arguments[0]instanceof e)i=arguments[0];else{if(!s.$target||!!/body/i.test(s.$target.selector))return!1;i=s.$target}if(i.length<1)return t.console&&console.error("element not valid",i),!1;n=e(s.template.expose),s.$body.append(n),n.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),r=e(s.template.exposeCover),u={zIndex:i.css("z-index"),position:i.css("position")},i.css("z-index",n.css("z-index")*1+1),u.position=="static"&&i.css("position","relative"),i.data("expose-css",u),r.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),s.$body.append(r),n.addClass(a),r.addClass(a),s.tipSettings.exposeClass&&(n.addClass(s.tipSettings.exposeClass),r.addClass(s.tipSettings.exposeClass)),i.data("expose",a),s.postExposeCallback(s.$li.index(),s.$next_tip,i),o.add_exposed(i)},un_expose:function(){var n,r,i,u,a=!1;if(arguments.length>0&&arguments[0]instanceof e)r=arguments[0];else{if(!s.$target||!!/body/i.test(s.$target.selector))return!1;r=s.$target}if(r.length<1)return t.console&&console.error("element not valid",r),!1;n=r.data("expose"),i=e("."+n),arguments.length>1&&(a=arguments[1]),a===!0?e(".joyride-expose-wrapper,.joyride-expose-cover").remove():i.remove(),u=r.data("expose-css"),u.zIndex=="auto"?r.css("z-index",""):r.css("z-index",u.zIndex),u.position!=r.css("position")&&(u.position=="static"?r.css("position",""):r.css("position",u.position)),r.removeData("expose"),r.removeData("expose-z-index"),o.remove_exposed(r)},add_exposed:function(t){s.exposed=s.exposed||[],t instanceof e?s.exposed.push(t[0]):typeof t=="string"&&s.exposed.push(t)},remove_exposed:function(t){var n;t instanceof e?n=t[0]:typeof t=="string"&&(n=t),s.exposed=s.exposed||[];for(var r=0;r<s.exposed.length;r++)if(s.exposed[r]==n){s.exposed.splice(r,1);return}},center:function(){var e=s.$window;return s.$next_tip.css({top:(e.height()-s.$next_tip.outerHeight())/2+e.scrollTop(),left:(e.width()-s.$next_tip.outerWidth())/2+e.scrollLeft()}),!0},bottom:function(){return/bottom/i.test(s.tipSettings.tipLocation)},top:function(){return/top/i.test(s.tipSettings.tipLocation)},right:function(){return/right/i.test(s.tipSettings.tipLocation)},left:function(){return/left/i.test(s.tipSettings.tipLocation)},corners:function(e){var t=s.$window,n=t.height()/2,r=Math.ceil(s.$target.offset().top-n+s.$next_tip.outerHeight()),i=t.width()+t.scrollLeft(),o=t.height()+r,u=t.height()+t.scrollTop(),a=t.scrollTop();return r<a&&(r<0?a=0:a=r),o>u&&(u=o),[e.offset().top<a,i<e.offset().left+e.outerWidth(),u<e.offset().top+e.outerHeight(),t.scrollLeft()>e.offset().left]},visible:function(e){var t=e.length;while(t--)if(e[t])return!1;return!0},nub_position:function(e,t,n){t==="auto"?e.addClass(n):e.addClass(t)},startTimer:function(){s.$li.length?s.automate=setTimeout(function(){o.hide(),o.show(),o.startTimer()},s.timer):clearTimeout(s.automate)},end:function(){s.cookieMonster&&e.cookie(s.cookieName,"ridden",{expires:365,domain:s.cookieDomain,path:s.cookiePath}),s.localStorage&&localStorage.setItem(s.localStorageKey,!0),s.timer>0&&clearTimeout(s.automate),s.modal&&s.expose&&o.un_expose(),s.$current_tip&&s.$current_tip.hide(),s.$li&&(s.postStepCallback(s.$li.index(),s.$current_tip),s.postRideCallback(s.$li.index(),s.$current_tip)),e(".joyride-modal-bg").hide()},jquery_check:function(){return e.isFunction(e.fn.on)?!0:(e.fn.on=function(e,t,n){return this.delegate(t,e,n)},e.fn.off=function(e,t,n){return this.undelegate(t,e,n)},!1)},outerHTML:function(e){return e.outerHTML||(new XMLSerializer).serializeToString(e)},version:function(){return s.version},tabbable:function(t){e(t).on("keydown",function(n){if(!n.isDefaultPrevented()&&n.keyCode&&n.keyCode===27){n.preventDefault(),o.end();return}if(n.keyCode!==9)return;var r=e(t).find(":tabbable"),i=r.filter(":first"),s=r.filter(":last");n.target===s[0]&&!n.shiftKey?(i.focus(1),n.preventDefault()):n.target===i[0]&&n.shiftKey&&(s.focus(1),n.preventDefault())})}};e.fn.joyride=function(t){if(o[t])return o[t].apply(this,Array.prototype.slice.call(arguments,1));if(typeof t=="object"||!t)return o.init.apply(this,arguments);e.error("Method "+t+" does not exist on jQuery.joyride")}})(jQuery,this);
;
/**
* @file
* Attaches behaviors for the Tour module's toolbar tab.
*/
(function ($, Backbone, Drupal, document) {
'use strict';
var queryString = decodeURI(window.location.search);
/**
* Attaches the tour's toolbar tab behavior.
*
* It uses the query string for:
* - tour: When ?tour=1 is present, the tour will start automatically after
* the page has loaded.
* - tips: Pass ?tips=class in the url to filter the available tips to the
* subset which match the given class.
*
* @example
* http://example.com/foo?tour=1&tips=bar
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attach tour functionality on `tour` events.
*/
Drupal.behaviors.tour = {
attach: function (context) {
$('body').once('tour').each(function () {
var model = new Drupal.tour.models.StateModel();
new Drupal.tour.views.ToggleTourView({
el: $(context).find('#toolbar-tab-tour'),
model: model
});
model
// Allow other scripts to respond to tour events.
.on('change:isActive', function (model, isActive) {
$(document).trigger((isActive) ? 'drupalTourStarted' : 'drupalTourStopped');
})
// Initialization: check whether a tour is available on the current
// page.
.set('tour', $(context).find('ol#tour'));
// Start the tour immediately if toggled via query string.
if (/tour=?/i.test(queryString)) {
model.set('isActive', true);
}
});
}
};
/**
* @namespace
*/
Drupal.tour = Drupal.tour || {
/**
* @namespace Drupal.tour.models
*/
models: {},
/**
* @namespace Drupal.tour.views
*/
views: {}
};
/**
* Backbone Model for tours.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.tour.models.StateModel = Backbone.Model.extend(/** @lends Drupal.tour.models.StateModel# */{
/**
* @type {object}
*/
defaults: /** @lends Drupal.tour.models.StateModel# */{
/**
* Indicates whether the Drupal root window has a tour.
*
* @type {Array}
*/
tour: [],
/**
* Indicates whether the tour is currently running.
*
* @type {bool}
*/
isActive: false,
/**
* Indicates which tour is the active one (necessary to cleanly stop).
*
* @type {Array}
*/
activeTour: []
}
});
Drupal.tour.views.ToggleTourView = Backbone.View.extend(/** @lends Drupal.tour.views.ToggleTourView# */{
/**
* @type {object}
*/
events: {click: 'onClick'},
/**
* Handles edit mode toggle interactions.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:tour change:isActive', this.render);
this.listenTo(this.model, 'change:isActive', this.toggleTour);
},
/**
* @inheritdoc
*
* @return {Drupal.tour.views.ToggleTourView}
* The `ToggleTourView` view.
*/
render: function () {
// Render the visibility.
this.$el.toggleClass('hidden', this._getTour().length === 0);
// Render the state.
var isActive = this.model.get('isActive');
this.$el.find('button')
.toggleClass('is-active', isActive)
.prop('aria-pressed', isActive);
return this;
},
/**
* Model change handler; starts or stops the tour.
*/
toggleTour: function () {
if (this.model.get('isActive')) {
var $tour = this._getTour();
this._removeIrrelevantTourItems($tour, this._getDocument());
var that = this;
if ($tour.find('li').length) {
$tour.joyride({
autoStart: true,
postRideCallback: function () { that.model.set('isActive', false); },
// HTML segments for tip layout.
template: {
link: '<a href=\"#close\" class=\"joyride-close-tip\">×</a>',
button: '<a href=\"#\" class=\"button button--primary joyride-next-tip\"></a>'
}
});
this.model.set({isActive: true, activeTour: $tour});
}
}
else {
this.model.get('activeTour').joyride('destroy');
this.model.set({isActive: false, activeTour: []});
}
},
/**
* Toolbar tab click event handler; toggles isActive.
*
* @param {jQuery.Event} event
* The click event.
*/
onClick: function (event) {
this.model.set('isActive', !this.model.get('isActive'));
event.preventDefault();
event.stopPropagation();
},
/**
* Gets the tour.
*
* @return {jQuery}
* A jQuery element pointing to a `<ol>` containing tour items.
*/
_getTour: function () {
return this.model.get('tour');
},
/**
* Gets the relevant document as a jQuery element.
*
* @return {jQuery}
* A jQuery element pointing to the document within which a tour would be
* started given the current state.
*/
_getDocument: function () {
return $(document);
},
/**
* Removes tour items for elements that don't have matching page elements.
*
* Or that are explicitly filtered out via the 'tips' query string.
*
* @example
* <caption>This will filter out tips that do not have a matching
* page element or don't have the "bar" class.</caption>
* http://example.com/foo?tips=bar
*
* @param {jQuery} $tour
* A jQuery element pointing to a `<ol>` containing tour items.
* @param {jQuery} $document
* A jQuery element pointing to the document within which the elements
* should be sought.
*
* @see Drupal.tour.views.ToggleTourView#_getDocument
*/
_removeIrrelevantTourItems: function ($tour, $document) {
var removals = false;
var tips = /tips=([^&]+)/.exec(queryString);
$tour
.find('li')
.each(function () {
var $this = $(this);
var itemId = $this.attr('data-id');
var itemClass = $this.attr('data-class');
// If the query parameter 'tips' is set, remove all tips that don't
// have the matching class.
if (tips && !$(this).hasClass(tips[1])) {
removals = true;
$this.remove();
return;
}
// Remove tip from the DOM if there is no corresponding page element.
if ((!itemId && !itemClass) ||
(itemId && $document.find('#' + itemId).length) ||
(itemClass && $document.find('.' + itemClass).length)) {
return;
}
removals = true;
$this.remove();
});
// If there were removals, we'll have to do some clean-up.
if (removals) {
var total = $tour.find('li').length;
if (!total) {
this.model.set({tour: []});
}
$tour
.find('li')
// Rebuild the progress data.
.each(function (index) {
var progress = Drupal.t('!tour_item of !total', {'!tour_item': index + 1, '!total': total});
$(this).find('.tour-progress').text(progress);
})
// Update the last item to have "End tour" as the button.
.eq(-1)
.attr('data-text', Drupal.t('End tour'));
}
}
});
})(jQuery, Backbone, Drupal, document);
;
/**
* @file
* Manages page tabbing modifications made by modules.
*/
/**
* Allow modules to respond to the constrain event.
*
* @event drupalTabbingConstrained
*/
/**
* Allow modules to respond to the tabbingContext release event.
*
* @event drupalTabbingContextReleased
*/
/**
* Allow modules to respond to the constrain event.
*
* @event drupalTabbingContextActivated
*/
/**
* Allow modules to respond to the constrain event.
*
* @event drupalTabbingContextDeactivated
*/
(function ($, Drupal) {
'use strict';
/**
* Provides an API for managing page tabbing order modifications.
*
* @constructor Drupal~TabbingManager
*/
function TabbingManager() {
/**
* Tabbing sets are stored as a stack. The active set is at the top of the
* stack. We use a JavaScript array as if it were a stack; we consider the
* first element to be the bottom and the last element to be the top. This
* allows us to use JavaScript's built-in Array.push() and Array.pop()
* methods.
*
* @type {Array.<Drupal~TabbingContext>}
*/
this.stack = [];
}
/**
* Add public methods to the TabbingManager class.
*/
$.extend(TabbingManager.prototype, /** @lends Drupal~TabbingManager# */{
/**
* Constrain tabbing to the specified set of elements only.
*
* Makes elements outside of the specified set of elements unreachable via
* the tab key.
*
* @param {jQuery} elements
* The set of elements to which tabbing should be constrained. Can also
* be a jQuery-compatible selector string.
*
* @return {Drupal~TabbingContext}
* The TabbingContext instance.
*
* @fires event:drupalTabbingConstrained
*/
constrain: function (elements) {
// Deactivate all tabbingContexts to prepare for the new constraint. A
// tabbingContext instance will only be reactivated if the stack is
// unwound to it in the _unwindStack() method.
var il = this.stack.length;
for (var i = 0; i < il; i++) {
this.stack[i].deactivate();
}
// The "active tabbing set" are the elements tabbing should be constrained
// to.
var $elements = $(elements).find(':tabbable').addBack(':tabbable');
var tabbingContext = new TabbingContext({
// The level is the current height of the stack before this new
// tabbingContext is pushed on top of the stack.
level: this.stack.length,
$tabbableElements: $elements
});
this.stack.push(tabbingContext);
// Activates the tabbingContext; this will manipulate the DOM to constrain
// tabbing.
tabbingContext.activate();
// Allow modules to respond to the constrain event.
$(document).trigger('drupalTabbingConstrained', tabbingContext);
return tabbingContext;
},
/**
* Restores a former tabbingContext when an active one is released.
*
* The TabbingManager stack of tabbingContext instances will be unwound
* from the top-most released tabbingContext down to the first non-released
* tabbingContext instance. This non-released instance is then activated.
*/
release: function () {
// Unwind as far as possible: find the topmost non-released
// tabbingContext.
var toActivate = this.stack.length - 1;
while (toActivate >= 0 && this.stack[toActivate].released) {
toActivate--;
}
// Delete all tabbingContexts after the to be activated one. They have
// already been deactivated, so their effect on the DOM has been reversed.
this.stack.splice(toActivate + 1);
// Get topmost tabbingContext, if one exists, and activate it.
if (toActivate >= 0) {
this.stack[toActivate].activate();
}
},
/**
* Makes all elements outside of the tabbingContext's set untabbable.
*
* Elements made untabbable have their original tabindex and autofocus
* values stored so that they might be restored later when this
* tabbingContext is deactivated.
*
* @param {Drupal~TabbingContext} tabbingContext
* The TabbingContext instance that has been activated.
*/
activate: function (tabbingContext) {
var $set = tabbingContext.$tabbableElements;
var level = tabbingContext.level;
// Determine which elements are reachable via tabbing by default.
var $disabledSet = $(':tabbable')
// Exclude elements of the active tabbing set.
.not($set);
// Set the disabled set on the tabbingContext.
tabbingContext.$disabledElements = $disabledSet;
// Record the tabindex for each element, so we can restore it later.
var il = $disabledSet.length;
for (var i = 0; i < il; i++) {
this.recordTabindex($disabledSet.eq(i), level);
}
// Make all tabbable elements outside of the active tabbing set
// unreachable.
$disabledSet
.prop('tabindex', -1)
.prop('autofocus', false);
// Set focus on an element in the tabbingContext's set of tabbable
// elements. First, check if there is an element with an autofocus
// attribute. Select the last one from the DOM order.
var $hasFocus = $set.filter('[autofocus]').eq(-1);
// If no element in the tabbable set has an autofocus attribute, select
// the first element in the set.
if ($hasFocus.length === 0) {
$hasFocus = $set.eq(0);
}
$hasFocus.trigger('focus');
},
/**
* Restores that tabbable state of a tabbingContext's disabled elements.
*
* Elements that were made untabbable have their original tabindex and
* autofocus values restored.
*
* @param {Drupal~TabbingContext} tabbingContext
* The TabbingContext instance that has been deactivated.
*/
deactivate: function (tabbingContext) {
var $set = tabbingContext.$disabledElements;
var level = tabbingContext.level;
var il = $set.length;
for (var i = 0; i < il; i++) {
this.restoreTabindex($set.eq(i), level);
}
},
/**
* Records the tabindex and autofocus values of an untabbable element.
*
* @param {jQuery} $el
* The set of elements that have been disabled.
* @param {number} level
* The stack level for which the tabindex attribute should be recorded.
*/
recordTabindex: function ($el, level) {
var tabInfo = $el.data('drupalOriginalTabIndices') || {};
tabInfo[level] = {
tabindex: $el[0].getAttribute('tabindex'),
autofocus: $el[0].hasAttribute('autofocus')
};
$el.data('drupalOriginalTabIndices', tabInfo);
},
/**
* Restores the tabindex and autofocus values of a reactivated element.
*
* @param {jQuery} $el
* The element that is being reactivated.
* @param {number} level
* The stack level for which the tabindex attribute should be restored.
*/
restoreTabindex: function ($el, level) {
var tabInfo = $el.data('drupalOriginalTabIndices');
if (tabInfo && tabInfo[level]) {
var data = tabInfo[level];
if (data.tabindex) {
$el[0].setAttribute('tabindex', data.tabindex);
}
// If the element did not have a tabindex at this stack level then
// remove it.
else {
$el[0].removeAttribute('tabindex');
}
if (data.autofocus) {
$el[0].setAttribute('autofocus', 'autofocus');
}
// Clean up $.data.
if (level === 0) {
// Remove all data.
$el.removeData('drupalOriginalTabIndices');
}
else {
// Remove the data for this stack level and higher.
var levelToDelete = level;
while (tabInfo.hasOwnProperty(levelToDelete)) {
delete tabInfo[levelToDelete];
levelToDelete++;
}
$el.data('drupalOriginalTabIndices', tabInfo);
}
}
}
});
/**
* Stores a set of tabbable elements.
*
* This constraint can be removed with the release() method.
*
* @constructor Drupal~TabbingContext
*
* @param {object} options
* A set of initiating values
* @param {number} options.level
* The level in the TabbingManager's stack of this tabbingContext.
* @param {jQuery} options.$tabbableElements
* The DOM elements that should be reachable via the tab key when this
* tabbingContext is active.
* @param {jQuery} options.$disabledElements
* The DOM elements that should not be reachable via the tab key when this
* tabbingContext is active.
* @param {bool} options.released
* A released tabbingContext can never be activated again. It will be
* cleaned up when the TabbingManager unwinds its stack.
* @param {bool} options.active
* When true, the tabbable elements of this tabbingContext will be reachable
* via the tab key and the disabled elements will not. Only one
* tabbingContext can be active at a time.
*/
function TabbingContext(options) {
$.extend(this, /** @lends Drupal~TabbingContext# */{
/**
* @type {?number}
*/
level: null,
/**
* @type {jQuery}
*/
$tabbableElements: $(),
/**
* @type {jQuery}
*/
$disabledElements: $(),
/**
* @type {bool}
*/
released: false,
/**
* @type {bool}
*/
active: false
}, options);
}
/**
* Add public methods to the TabbingContext class.
*/
$.extend(TabbingContext.prototype, /** @lends Drupal~TabbingContext# */{
/**
* Releases this TabbingContext.
*
* Once a TabbingContext object is released, it can never be activated
* again.
*
* @fires event:drupalTabbingContextReleased
*/
release: function () {
if (!this.released) {
this.deactivate();
this.released = true;
Drupal.tabbingManager.release(this);
// Allow modules to respond to the tabbingContext release event.
$(document).trigger('drupalTabbingContextReleased', this);
}
},
/**
* Activates this TabbingContext.
*
* @fires event:drupalTabbingContextActivated
*/
activate: function () {
// A released TabbingContext object can never be activated again.
if (!this.active && !this.released) {
this.active = true;
Drupal.tabbingManager.activate(this);
// Allow modules to respond to the constrain event.
$(document).trigger('drupalTabbingContextActivated', this);
}
},
/**
* Deactivates this TabbingContext.
*
* @fires event:drupalTabbingContextDeactivated
*/
deactivate: function () {
if (this.active) {
this.active = false;
Drupal.tabbingManager.deactivate(this);
// Allow modules to respond to the constrain event.
$(document).trigger('drupalTabbingContextDeactivated', this);
}
}
});
// Mark this behavior as processed on the first pass and return if it is
// already processed.
if (Drupal.tabbingManager) {
return;
}
/**
* @type {Drupal~TabbingManager}
*/
Drupal.tabbingManager = new TabbingManager();
}(jQuery, Drupal));
;
/**
* @file
* Attaches behaviors for the Contextual module's edit toolbar tab.
*/
(function ($, Drupal, Backbone) {
'use strict';
var strings = {
tabbingReleased: Drupal.t('Tabbing is no longer constrained by the Contextual module.'),
tabbingConstrained: Drupal.t('Tabbing is constrained to a set of @contextualsCount and the edit mode toggle.'),
pressEsc: Drupal.t('Press the esc key to exit.')
};
/**
* Initializes a contextual link: updates its DOM, sets up model and views.
*
* @param {HTMLElement} context
* A contextual links DOM element as rendered by the server.
*/
function initContextualToolbar(context) {
if (!Drupal.contextual || !Drupal.contextual.collection) {
return;
}
var contextualToolbar = Drupal.contextualToolbar;
var model = contextualToolbar.model = new contextualToolbar.StateModel({
// Checks whether localStorage indicates we should start in edit mode
// rather than view mode.
// @see Drupal.contextualToolbar.VisualView.persist
isViewing: localStorage.getItem('Drupal.contextualToolbar.isViewing') !== 'false'
}, {
contextualCollection: Drupal.contextual.collection
});
var viewOptions = {
el: $('.toolbar .toolbar-bar .contextual-toolbar-tab'),
model: model,
strings: strings
};
new contextualToolbar.VisualView(viewOptions);
new contextualToolbar.AuralView(viewOptions);
}
/**
* Attaches contextual's edit toolbar tab behavior.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches contextual toolbar behavior on a contextualToolbar-init event.
*/
Drupal.behaviors.contextualToolbar = {
attach: function (context) {
if ($('body').once('contextualToolbar-init').length) {
initContextualToolbar(context);
}
}
};
/**
* Namespace for the contextual toolbar.
*
* @namespace
*/
Drupal.contextualToolbar = {
/**
* The {@link Drupal.contextualToolbar.StateModel} instance.
*
* @type {?Drupal.contextualToolbar.StateModel}
*/
model: null
};
})(jQuery, Drupal, Backbone);
;
/**
* @file
* A Backbone Model for the state of Contextual module's edit toolbar tab.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextualToolbar.StateModel = Backbone.Model.extend(/** @lends Drupal.contextualToolbar.StateModel# */{
/**
* @type {object}
*
* @prop {bool} isViewing
* @prop {bool} isVisible
* @prop {number} contextualCount
* @prop {Drupal~TabbingContext} tabbingContext
*/
defaults: /** @lends Drupal.contextualToolbar.StateModel# */{
/**
* Indicates whether the toggle is currently in "view" or "edit" mode.
*
* @type {bool}
*/
isViewing: true,
/**
* Indicates whether the toggle should be visible or hidden. Automatically
* calculated, depends on contextualCount.
*
* @type {bool}
*/
isVisible: false,
/**
* Tracks how many contextual links exist on the page.
*
* @type {number}
*/
contextualCount: 0,
/**
* A TabbingContext object as returned by {@link Drupal~TabbingManager}:
* the set of tabbable elements when edit mode is enabled.
*
* @type {?Drupal~TabbingContext}
*/
tabbingContext: null
},
/**
* Models the state of the edit mode toggle.
*
* @constructs
*
* @augments Backbone.Model
*
* @param {object} attrs
* Attributes for the backbone model.
* @param {object} options
* An object with the following option:
* @param {Backbone.collection} options.contextualCollection
* The collection of {@link Drupal.contextual.StateModel} models that
* represent the contextual links on the page.
*/
initialize: function (attrs, options) {
// Respond to new/removed contextual links.
this.listenTo(options.contextualCollection, 'reset remove add', this.countContextualLinks);
this.listenTo(options.contextualCollection, 'add', this.lockNewContextualLinks);
// Automatically determine visibility.
this.listenTo(this, 'change:contextualCount', this.updateVisibility);
// Whenever edit mode is toggled, lock all contextual links.
this.listenTo(this, 'change:isViewing', function (model, isViewing) {
options.contextualCollection.each(function (contextualModel) {
contextualModel.set('isLocked', !isViewing);
});
});
},
/**
* Tracks the number of contextual link models in the collection.
*
* @param {Drupal.contextual.StateModel} contextualModel
* The contextual links model that was added or removed.
* @param {Backbone.Collection} contextualCollection
* The collection of contextual link models.
*/
countContextualLinks: function (contextualModel, contextualCollection) {
this.set('contextualCount', contextualCollection.length);
},
/**
* Lock newly added contextual links if edit mode is enabled.
*
* @param {Drupal.contextual.StateModel} contextualModel
* The contextual links model that was added.
* @param {Backbone.Collection} [contextualCollection]
* The collection of contextual link models.
*/
lockNewContextualLinks: function (contextualModel, contextualCollection) {
if (!this.get('isViewing')) {
contextualModel.set('isLocked', true);
}
},
/**
* Automatically updates visibility of the view/edit mode toggle.
*/
updateVisibility: function () {
this.set('isVisible', this.get('contextualCount') > 0);
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides the aural view of the edit mode toggle.
*/
(function ($, Drupal, Backbone, _) {
'use strict';
Drupal.contextualToolbar.AuralView = Backbone.View.extend(/** @lends Drupal.contextualToolbar.AuralView# */{
/**
* Tracks whether the tabbing constraint announcement has been read once.
*
* @type {bool}
*/
announcedOnce: false,
/**
* Renders the aural view of the edit mode toggle (screen reader support).
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
*/
initialize: function (options) {
this.options = options;
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'change:isViewing', this.manageTabbing);
$(document).on('keyup', _.bind(this.onKeypress, this));
},
/**
* @inheritdoc
*
* @return {Drupal.contextualToolbar.AuralView}
* The current contextual toolbar aural view.
*/
render: function () {
// Render the state.
this.$el.find('button').attr('aria-pressed', !this.model.get('isViewing'));
return this;
},
/**
* Limits tabbing to the contextual links and edit mode toolbar tab.
*/
manageTabbing: function () {
var tabbingContext = this.model.get('tabbingContext');
// Always release an existing tabbing context.
if (tabbingContext) {
tabbingContext.release();
Drupal.announce(this.options.strings.tabbingReleased);
}
// Create a new tabbing context when edit mode is enabled.
if (!this.model.get('isViewing')) {
tabbingContext = Drupal.tabbingManager.constrain($('.contextual-toolbar-tab, .contextual'));
this.model.set('tabbingContext', tabbingContext);
this.announceTabbingConstraint();
this.announcedOnce = true;
}
},
/**
* Announces the current tabbing constraint.
*/
announceTabbingConstraint: function () {
var strings = this.options.strings;
Drupal.announce(Drupal.formatString(strings.tabbingConstrained, {
'@contextualsCount': Drupal.formatPlural(Drupal.contextual.collection.length, '@count contextual link', '@count contextual links')
}));
Drupal.announce(strings.pressEsc);
},
/**
* Responds to esc and tab key press events.
*
* @param {jQuery.Event} event
* The keypress event.
*/
onKeypress: function (event) {
// The first tab key press is tracked so that an annoucement about tabbing
// constraints can be raised if edit mode is enabled when the page is
// loaded.
if (!this.announcedOnce && event.keyCode === 9 && !this.model.get('isViewing')) {
this.announceTabbingConstraint();
// Set announce to true so that this conditional block won't run again.
this.announcedOnce = true;
}
// Respond to the ESC key. Exit out of edit mode.
if (event.keyCode === 27) {
this.model.set('isViewing', true);
}
}
});
})(jQuery, Drupal, Backbone, _);
;
/**
* @file
* A Backbone View that provides the visual view of the edit mode toggle.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextualToolbar.VisualView = Backbone.View.extend(/** @lends Drupal.contextualToolbar.VisualView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
return {
click: function () {
this.model.set('isViewing', !this.model.get('isViewing'));
},
touchend: touchEndToClick
};
},
/**
* Renders the visual view of the edit mode toggle.
*
* Listens to mouse & touch and handles edit mode toggle interactions.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'change:isViewing', this.persist);
},
/**
* @inheritdoc
*
* @return {Drupal.contextualToolbar.VisualView}
* The current contextual toolbar visual view.
*/
render: function () {
// Render the visibility.
this.$el.toggleClass('hidden', !this.model.get('isVisible'));
// Render the state.
this.$el.find('button').toggleClass('is-active', !this.model.get('isViewing'));
return this;
},
/**
* Model change handler; persists the isViewing value to localStorage.
*
* `isViewing === true` is the default, so only stores in localStorage when
* it's not the default value (i.e. false).
*
* @param {Drupal.contextualToolbar.StateModel} model
* A {@link Drupal.contextualToolbar.StateModel} model.
* @param {bool} isViewing
* The value of the isViewing attribute in the model.
*/
persist: function (model, isViewing) {
if (!isViewing) {
localStorage.setItem('Drupal.contextualToolbar.isViewing', 'false');
}
else {
localStorage.removeItem('Drupal.contextualToolbar.isViewing');
}
}
});
})(Drupal, Backbone);
;
/**
* @file
* Replaces the home link in toolbar with a back to site link.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
var pathInfo = drupalSettings.path;
var escapeAdminPath = sessionStorage.getItem('escapeAdminPath');
var windowLocation = window.location;
// Saves the last non-administrative page in the browser to be able to link
// back to it when browsing administrative pages. If there is a destination
// parameter there is not need to save the current path because the page is
// loaded within an existing "workflow".
if (!pathInfo.currentPathIsAdmin && !/destination=/.test(windowLocation.search)) {
sessionStorage.setItem('escapeAdminPath', windowLocation);
}
/**
* Replaces the "Home" link with "Back to site" link.
*
* Back to site link points to the last non-administrative page the user
* visited within the same browser tab.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the replacement functionality to the toolbar-escape-admin element.
*/
Drupal.behaviors.escapeAdmin = {
attach: function () {
var $toolbarEscape = $('[data-toolbar-escape-admin]').once('escapeAdmin');
if ($toolbarEscape.length && pathInfo.currentPathIsAdmin) {
if (escapeAdminPath !== null) {
$toolbarEscape.attr('href', escapeAdminPath);
}
else {
$toolbarEscape.text(Drupal.t('Home'));
}
$toolbarEscape.closest('.toolbar-tab').removeClass('hidden');
}
}
};
})(jQuery, Drupal, drupalSettings);
;
|
src/svg-icons/device/dvr.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceDvr = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12zm-2-9H8v2h11V8zm0 4H8v2h11v-2zM7 8H5v2h2V8zm0 4H5v2h2v-2z"/>
</SvgIcon>
);
DeviceDvr = pure(DeviceDvr);
DeviceDvr.displayName = 'DeviceDvr';
DeviceDvr.muiName = 'SvgIcon';
export default DeviceDvr;
|
src/containers/DevTools/DevTools.js | yomolify/cc_material | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="H"
changePositionKey="Q">
<LogMonitor />
</DockMonitor>
);
|
docs-ui/components/confirm.stories.js | mvaled/sentry | import React from 'react';
import {storiesOf} from '@storybook/react';
import {withInfo} from '@storybook/addon-info';
import {action} from '@storybook/addon-actions';
import Confirm from 'app/components/confirm';
import Button from 'app/components/button';
storiesOf('UI|Confirm', module).add(
'Confirm',
withInfo({
text:
'Component whose child is rendered as the "action" component that when clicked opens the "Confirm Modal"',
propTablesExclude: [Button],
})(() => (
<div>
<Confirm
onConfirm={action('confirmed')}
message="Are you sure you want to do this?"
>
<Button priority="primary">Confirm on Button click</Button>
</Confirm>
</div>
))
);
|
fields/types/password/PasswordField.js | kumo/keystone | import React from 'react';
import Field from '../Field';
import { Button, FormInput, InputGroup } from 'elemental';
module.exports = Field.create({
displayName: 'PasswordField',
getInitialState () {
return {
passwordIsSet: this.props.value ? true : false,
showChangeUI: this.props.mode === 'create' ? true : false,
password: '',
confirm: ''
};
},
valueChanged (which, event) {
var newState = {};
newState[which] = event.target.value;
this.setState(newState);
},
showChangeUI () {
this.setState({
showChangeUI: true
}, () => this.focus());
},
onCancel () {
this.setState({
showChangeUI: false
}, () => this.focus());
},
renderValue () {
return <FormInput noedit>{this.props.value ? 'password set' : 'password not set'}</FormInput>;
},
renderField () {
return this.state.showChangeUI ? this.renderFields() : this.renderChangeButton();
},
renderFields () {
return (
<InputGroup>
<InputGroup.Section grow>
<FormInput type="password" name={this.props.path} placeholder="New password" ref="focusTarget" value={this.state.password} onChange={this.valueChanged.bind(this, 'password')} autoComplete="off" />
</InputGroup.Section>
<InputGroup.Section grow>
<FormInput type="password" name={this.props.paths.confirm} placeholder="Confirm new password" value={this.state.confirm} onChange={this.valueChanged.bind(this, 'confirm')} autoComplete="off" />
</InputGroup.Section>
{this.state.passwordIsSet ? <InputGroup.Section><Button onClick={this.onCancel}>Cancel</Button></InputGroup.Section> : null}
</InputGroup>
);
},
renderChangeButton () {
var label = this.state.passwordIsSet ? 'Change Password' : 'Set Password';
return (
<Button ref="focusTarget" onClick={this.showChangeUI}>{label}</Button>
);
}
});
|
ui/node_modules/react-bootstrap/src/SplitButton.js | bpatters/eservice | import React from 'react';
import classSet from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import DropdownStateMixin from './DropdownStateMixin';
import Button from './Button';
import ButtonGroup from './ButtonGroup';
import DropdownMenu from './DropdownMenu';
const SplitButton = React.createClass({
mixins: [BootstrapMixin, DropdownStateMixin],
propTypes: {
pullRight: React.PropTypes.bool,
title: React.PropTypes.node,
href: React.PropTypes.string,
target: React.PropTypes.string,
dropdownTitle: React.PropTypes.node,
onClick: React.PropTypes.func,
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool
},
getDefaultProps() {
return {
dropdownTitle: 'Toggle dropdown'
};
},
render() {
let groupClasses = {
'open': this.state.open,
'dropup': this.props.dropup
};
let button = (
<Button
{...this.props}
ref="button"
onClick={this.handleButtonClick}
title={null}
id={null}>
{this.props.title}
</Button>
);
let dropdownButton = (
<Button
{...this.props}
ref="dropdownButton"
className={classSet(this.props.className, 'dropdown-toggle')}
onClick={this.handleDropdownClick}
title={null}
href={null}
target={null}
id={null}>
<span className="sr-only">{this.props.dropdownTitle}</span>
<span className="caret" />
<span style={{letterSpacing: '-.3em'}}> </span>
</Button>
);
return (
<ButtonGroup
bsSize={this.props.bsSize}
className={classSet(groupClasses)}
id={this.props.id}>
{button}
{dropdownButton}
<DropdownMenu
ref="menu"
onSelect={this.handleOptionSelect}
aria-labelledby={this.props.id}
pullRight={this.props.pullRight}>
{this.props.children}
</DropdownMenu>
</ButtonGroup>
);
},
handleButtonClick(e) {
if (this.state.open) {
this.setDropdownState(false);
}
if (this.props.onClick) {
this.props.onClick(e, this.props.href, this.props.target);
}
},
handleDropdownClick(e) {
e.preventDefault();
this.setDropdownState(!this.state.open);
},
handleOptionSelect(key) {
if (this.props.onSelect) {
this.props.onSelect(key);
}
this.setDropdownState(false);
}
});
export default SplitButton;
|
admin/client/App/shared/Kbd.js | andrewlinfoot/keystone | import React from 'react';
import { css } from 'glamor';
import theme from '../../theme';
import { darken, lighten } from '../../utils/color';
function Kbd ({ className, ...props }) {
props.className = css(classes.kbd);
return <kbd {...props} />;
};
const classes = {
kbd: {
backgroundColor: theme.color.body,
borderRadius: 3,
border: `1px solid #ccc`,
borderBottomColor: darken('#ccc', 4),
borderTopColor: lighten('#ccc', 4),
boxShadow: `0 1px 1px rgba(0, 0, 0, 0.12), 0 2px 0 0 rgba(255, 255, 255, 0.7) inset`,
display: 'inline-block',
fontFamily: 'Consolas, "Liberation Mono", Courier, monospace',
fontSize: '0.85em',
fontWeight: 700,
lineHeight: 'inherit',
padding: '1px 4px',
whiteSpace: 'nowrap',
// little hack to tweak "visual-middle" alignment
position: 'relative',
top: -1,
},
};
module.exports = Kbd;
|
node_modules/react-icons/fa/minus-square.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const FaMinusSquare = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m31.6 21.4v-2.8q0-0.6-0.5-1t-1-0.5h-20q-0.5 0-1 0.5t-0.4 1v2.8q0 0.6 0.4 1t1 0.5h20q0.6 0 1-0.5t0.5-1z m5.7-12.1v21.4q0 2.7-1.9 4.6t-4.5 1.8h-21.5q-2.6 0-4.5-1.8t-1.9-4.6v-21.4q0-2.7 1.9-4.6t4.5-1.8h21.5q2.6 0 4.5 1.8t1.9 4.6z"/></g>
</Icon>
)
export default FaMinusSquare
|
ajax/libs/F2/1.3.0/f2.no-bootstrap.js | mwillerich/cdnjs | ;(function(exports) {
if (exports.F2 && !exports.F2_TESTING_MODE) {
return;
}
/*!
JSON.org requires the following notice to accompany json2:
Copyright (c) 2002 JSON.org
http://json.org
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
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.
*/
/*
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
/*!
* jQuery JavaScript Library v1.8.3
* The jQuery Foundation and other contributors require the following notice to accompany jQuery:
*
* Copyright (c) 2013 jQuery Foundation and other contributors
*
* http://jquery.com
*
* 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( 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 );
/*!
* This file creates $ and jQuery variables within the F2 closure scope
*/
var $, jQuery = $ = window.jQuery.noConflict(true);
/*!
* Hij1nx requires the following notice to accompany EventEmitter:
*
* Copyright (c) 2011 hij1nx
*
* http://www.twitter.com/hij1nx
*
* 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(exports, undefined) {
var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
var defaultMaxListeners = 10;
function init() {
this._events = new Object;
}
function configure(conf) {
if (conf) {
conf.delimiter && (this.delimiter = conf.delimiter);
conf.wildcard && (this.wildcard = conf.wildcard);
if (this.wildcard) {
this.listenerTree = new Object;
}
}
}
function EventEmitter(conf) {
this._events = new Object;
configure.call(this, conf);
}
//
// Attention, function return type now is array, always !
// It has zero elements if no any matches found and one or more
// elements (leafs) if there are matches
//
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
typeLength = type.length, currentType = type[i], nextType = type[i+1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
handlers && handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
handlers && handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
}
}
return listeners;
} else if(currentType === '**') {
endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
if(endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if(branch === '*' || branch === '**') {
if(tree[branch]._listeners && !endReached) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
} else if(branch === nextType) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i+1);
}
xxTree = tree['**'];
if(xxTree) {
if(i < typeLength) {
if(xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for(branch in xxTree) {
if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if(branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i+2);
} else if(branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i+1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
}
}
}
} else if(xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if(xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
function growListenerTree(type, listener) {
type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
//
// Looks for two consecutive '**', if so, don't add the event at all.
//
for(var i = 0, len = type.length; i+1 < len; i++) {
if(type[i] === '**' && type[i+1] === '**') {
return;
}
}
var tree = this.listenerTree;
var name = type.shift();
while (name) {
if (!tree[name]) {
tree[name] = new Object;
}
tree = tree[name];
if (type.length === 0) {
if (!tree._listeners) {
tree._listeners = listener;
}
else if(typeof tree._listeners === 'function') {
tree._listeners = [tree._listeners, listener];
}
else if (isArray(tree._listeners)) {
tree._listeners.push(listener);
if (!tree._listeners.warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && tree._listeners.length > m) {
tree._listeners.warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
tree._listeners.length);
console.trace();
}
}
}
return true;
}
name = type.shift();
}
return true;
};
// 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.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.delimiter = '.';
EventEmitter.prototype.setMaxListeners = function(n) {
this._events || init.call(this);
this._events.maxListeners = n;
};
EventEmitter.prototype.event = '';
EventEmitter.prototype.once = function(event, fn) {
this.many(event, 1, fn);
return this;
};
EventEmitter.prototype.many = function(event, ttl, fn) {
var self = this;
if (typeof fn !== 'function') {
throw new Error('many only accepts instances of Function');
}
function listener() {
if (--ttl === 0) {
self.off(event, listener);
}
fn.apply(this, arguments);
};
listener._origin = fn;
this.on(event, listener);
return self;
};
EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if (type === 'newListener') {
if (!this._events.newListener) { return false; }
}
// Loop through the *_all* functions and invoke them.
if (this._all) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
for (i = 0, l = this._all.length; i < l; i++) {
this.event = type;
this._all[i].apply(this, args);
}
}
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._all &&
!this._events.error &&
!(this.wildcard && this.listenerTree.error)) {
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
var handler;
if(this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
}
else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
if (arguments.length === 1) {
handler.call(this);
}
else if (arguments.length > 1)
switch (arguments.length) {
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
handler.apply(this, args);
}
return true;
}
else if (handler) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
this.event = type;
listeners[i].apply(this, args);
}
return (listeners.length > 0) || this._all;
}
else {
return this._all;
}
};
EventEmitter.prototype.on = function(type, listener) {
if (typeof type === 'function') {
this.onAny(type);
return this;
}
if (typeof listener !== 'function') {
throw new Error('on only accepts instances of Function');
}
this._events || init.call(this);
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if(this.wildcard) {
growListenerTree.call(this, type, listener);
return this;
}
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
}
else if(typeof this._events[type] === 'function') {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
else if (isArray(this._events[type])) {
// If we've already got an array, just append.
this._events[type].push(listener);
// Check for listener leak
if (!this._events[type].warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (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);
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.onAny = function(fn) {
if(!this._all) {
this._all = [];
}
if (typeof fn !== 'function') {
throw new Error('onAny only accepts instances of Function');
}
// Add the function to the event listener collection.
this._all.push(fn);
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function(type, listener) {
if (typeof listener !== 'function') {
throw new Error('removeListener only takes instances of Function');
}
var handlers,leafs=[];
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
}
else {
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events[type]) return this;
handlers = this._events[type];
leafs.push({_listeners:handlers});
}
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
handlers = leaf._listeners;
if (isArray(handlers)) {
var position = -1;
for (var i = 0, length = handlers.length; i < length; i++) {
if (handlers[i] === listener ||
(handlers[i].listener && handlers[i].listener === listener) ||
(handlers[i]._origin && handlers[i]._origin === listener)) {
position = i;
break;
}
}
if (position < 0) {
return this;
}
if(this.wildcard) {
leaf._listeners.splice(position, 1)
}
else {
this._events[type].splice(position, 1);
}
if (handlers.length === 0) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
else if (handlers === listener ||
(handlers.listener && handlers.listener === listener) ||
(handlers._origin && handlers._origin === listener)) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
return this;
};
EventEmitter.prototype.offAny = function(fn) {
var i = 0, l = 0, fns;
if (fn && this._all && this._all.length > 0) {
fns = this._all;
for(i = 0, l = fns.length; i < l; i++) {
if(fn === fns[i]) {
fns.splice(i, 1);
return this;
}
}
} else {
this._all = [];
}
return this;
};
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
!this._events || init.call(this);
return this;
}
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
leaf._listeners = null;
}
}
else {
if (!this._events[type]) return this;
this._events[type] = null;
}
return this;
};
EventEmitter.prototype.listeners = function(type) {
if(this.wildcard) {
var handlers = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
return handlers;
}
this._events || init.call(this);
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
EventEmitter.prototype.listenersAny = function() {
if(this._all) {
return this._all;
}
else {
return [];
}
};
// if (typeof define === 'function' && define.amd) {
// define('EventEmitter2', [], function() {
// return EventEmitter;
// });
// } else {
exports.EventEmitter2 = EventEmitter;
// }
}(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window);
/*!
* Øyvind Sean Kinsey and others require the following notice to accompany easyXDM:
*
* http://easyxdm.net/
* Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
*
* 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 (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) {
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */
var global = this;
var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded
var emptyFn = Function.prototype;
var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4)
var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression
var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global)
var easyXDM = {};
var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite
var IFRAME_PREFIX = "easyXDM_";
var HAS_NAME_PROPERTY_BUG;
var useHash = false; // whether to use the hash over the query
var flashVersion; // will be set if using flash
var HAS_FLASH_THROTTLED_BUG;
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
// end
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
function isArray(o){
return Object.prototype.toString.call(o) === '[object Array]';
}
// end
function hasFlash(){
try {
var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1);
HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0;
activeX = null;
return true;
}
catch (notSupportedException) {
return false;
}
}
/*
* Cross Browser implementation for adding and removing event listeners.
*/
var on, un;
if (isHostMethod(window, "addEventListener")) {
on = function(target, type, listener){
target.addEventListener(type, listener, false);
};
un = function(target, type, listener){
target.removeEventListener(type, listener, false);
};
}
else if (isHostMethod(window, "attachEvent")) {
on = function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
un = function(object, sEvent, fpNotify){
object.detachEvent("on" + sEvent, fpNotify);
};
}
else {
throw new Error("Browser not supported");
}
/*
* Cross Browser implementation of DOMContentLoaded.
*/
var domIsReady = false, domReadyQueue = [], readyState;
if ("readyState" in document) {
// If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and
// 'interactive' (HTML5 specs, recent WebKit builds) states.
// https://bugs.webkit.org/show_bug.cgi?id=45119
readyState = document.readyState;
domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive"));
}
else {
// If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately
// when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not.
// We only need a body to add elements to, so the existence of document.body is enough for us.
domIsReady = !!document.body;
}
function dom_onReady(){
if (domIsReady) {
return;
}
domIsReady = true;
for (var i = 0; i < domReadyQueue.length; i++) {
domReadyQueue[i]();
}
domReadyQueue.length = 0;
}
if (!domIsReady) {
if (isHostMethod(window, "addEventListener")) {
on(document, "DOMContentLoaded", dom_onReady);
}
else {
on(document, "readystatechange", function(){
if (document.readyState == "complete") {
dom_onReady();
}
});
if (document.documentElement.doScroll && window === top) {
var doScrollCheck = function(){
if (domIsReady) {
return;
}
// http://javascript.nwbox.com/IEContentLoaded/
try {
document.documentElement.doScroll("left");
}
catch (e) {
setTimeout(doScrollCheck, 1);
return;
}
dom_onReady();
};
doScrollCheck();
}
}
// A fallback to window.onload, that will always work
on(window, "load", dom_onReady);
}
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {Object} scope An optional scope for the function to be called with.
*/
function whenReady(fn, scope){
if (domIsReady) {
fn.call(scope);
return;
}
domReadyQueue.push(function(){
fn.call(scope);
});
}
/**
* Returns an instance of easyXDM from the parent window with
* respect to the namespace.
*
* @return An instance of easyXDM (in the parent window)
*/
function getParentObject(){
var obj = parent;
if (namespace !== "") {
for (var i = 0, ii = namespace.split("."); i < ii.length; i++) {
obj = obj[ii[i]];
}
}
return obj.easyXDM;
}
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
function noConflict(ns){
window.easyXDM = _easyXDM;
namespace = ns;
if (namespace) {
IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_";
}
return easyXDM;
}
/*
* Methods for working with URLs
*/
/**
* Get the domain name from a url.
* @param {String} url The url to extract the domain from.
* @return The domain part of the url.
* @type {String}
*/
function getDomainName(url){
return url.match(reURI)[3];
}
/**
* Get the port for a given URL, or "" if none
* @param {String} url The url to extract the port from.
* @return The port part of the url.
* @type {String}
*/
function getPort(url){
return url.match(reURI)[4] || "";
}
/**
* Returns a string containing the schema, domain and if present the port
* @param {String} url The url to extract the location from
* @return {String} The location part of the url
*/
function getLocation(url){
var m = url.toLowerCase().match(reURI);
var proto = m[2], domain = m[3], port = m[4] || "";
if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) {
port = "";
}
return proto + "//" + domain + port;
}
/**
* Resolves a relative url into an absolute one.
* @param {String} url The path to resolve.
* @return {String} The resolved url.
*/
function resolveUrl(url){
// replace all // except the one in proto with /
url = url.replace(reDoubleSlash, "$1/");
// If the url is a valid url we do nothing
if (!url.match(/^(http||https):\/\//)) {
// If this is a relative path
var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
if (path.substring(path.length - 1) !== "/") {
path = path.substring(0, path.lastIndexOf("/") + 1);
}
url = location.protocol + "//" + location.host + path + url;
}
// reduce all 'xyz/../' to just ''
while (reParent.test(url)) {
url = url.replace(reParent, "");
}
return url;
}
/**
* Appends the parameters to the given url.<br/>
* The base url can contain existing query parameters.
* @param {String} url The base url.
* @param {Object} parameters The parameters to add.
* @return {String} A new valid url with the parameters appended.
*/
function appendQueryParameters(url, parameters){
var hash = "", indexOf = url.indexOf("#");
if (indexOf !== -1) {
hash = url.substring(indexOf);
url = url.substring(0, indexOf);
}
var q = [];
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
q.push(key + "=" + encodeURIComponent(parameters[key]));
}
}
return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash;
}
// build the query object either from location.query, if it contains the xdm_e argument, or from location.hash
var query = (function(input){
input = input.substring(1).split("&");
var data = {}, pair, i = input.length;
while (i--) {
pair = input[i].split("=");
data[pair[0]] = decodeURIComponent(pair[1]);
}
return data;
}(/xdm_e=/.test(location.search) ? location.search : location.hash));
/*
* Helper methods
*/
/**
* Helper for checking if a variable/property is undefined
* @param {Object} v The variable to test
* @return {Boolean} True if the passed variable is undefined
*/
function undef(v){
return typeof v === "undefined";
}
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
var getJSON = function(){
var cached = {};
var obj = {
a: [1, 2, 3]
}, json = "{\"a\":[1,2,3]}";
if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) {
// this is a working JSON instance
return JSON;
}
if (Object.toJSON) {
if (Object.toJSON(obj).replace((/\s/g), "") === json) {
// this is a working stringify method
cached.stringify = Object.toJSON;
}
}
if (typeof String.prototype.evalJSON === "function") {
obj = json.evalJSON();
if (obj.a && obj.a.length === 3 && obj.a[2] === 3) {
// this is a working parse method
cached.parse = function(str){
return str.evalJSON();
};
}
}
if (cached.stringify && cached.parse) {
// Only memoize the result if we have valid instance
getJSON = function(){
return cached;
};
return cached;
}
return null;
};
/**
* Applies properties from the source object to the target object.<br/>
* @param {Object} target The target of the properties.
* @param {Object} source The source of the properties.
* @param {Boolean} noOverwrite Set to True to only set non-existing properties.
*/
function apply(destination, source, noOverwrite){
var member;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (prop in destination) {
member = source[prop];
if (typeof member === "object") {
apply(destination[prop], member, noOverwrite);
}
else if (!noOverwrite) {
destination[prop] = source[prop];
}
}
else {
destination[prop] = source[prop];
}
}
}
return destination;
}
// This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName].
function testForNamePropertyBug(){
var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input"));
input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues
HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name];
document.body.removeChild(form);
}
/**
* Creates a frame and appends it to the DOM.
* @param config {object} This object can have the following properties
* <ul>
* <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li>
* <li> {object} attr The attributes that should be set on the frame.</li>
* <li> {DOMElement} container Its parent element (Optional).</li>
* <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li>
* </ul>
* @return The frames DOMElement
* @type DOMElement
*/
function createFrame(config){
if (undef(HAS_NAME_PROPERTY_BUG)) {
testForNamePropertyBug();
}
var frame;
// This is to work around the problems in IE6/7 with setting the name property.
// Internally this is set as 'submitName' instead when using 'iframe.name = ...'
// This is not required by easyXDM itself, but is to facilitate other use cases
if (HAS_NAME_PROPERTY_BUG) {
frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>");
}
else {
frame = document.createElement("IFRAME");
frame.name = config.props.name;
}
frame.id = frame.name = config.props.name;
delete config.props.name;
if (config.onLoad) {
on(frame, "load", config.onLoad);
}
if (typeof config.container == "string") {
config.container = document.getElementById(config.container);
}
if (!config.container) {
// This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers.
apply(frame.style, {
position: "absolute",
top: "-2000px"
});
config.container = document.body;
}
// HACK for some reason, IE needs the source set
// after the frame has been appended into the DOM
// so remove the src, and set it afterwards
var src = config.props.src;
delete config.props.src;
// transfer properties to the frame
apply(frame, config.props);
frame.border = frame.frameBorder = 0;
frame.allowTransparency = true;
config.container.appendChild(frame);
// HACK see above
frame.src = src;
config.props.src = src;
return frame;
}
/**
* Check whether a domain is allowed using an Access Control List.
* The ACL can contain * and ? as wildcards, or can be regular expressions.
* If regular expressions they need to begin with ^ and end with $.
* @param {Array/String} acl The list of allowed domains
* @param {String} domain The domain to test.
* @return {Boolean} True if the domain is allowed, false if not.
*/
function checkAcl(acl, domain){
// normalize into an array
if (typeof acl == "string") {
acl = [acl];
}
var re, i = acl.length;
while (i--) {
re = acl[i];
re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$"));
if (re.test(domain)) {
return true;
}
}
return false;
}
/*
* Functions related to stacks
*/
/**
* Prepares an array of stack-elements suitable for the current configuration
* @param {Object} config The Transports configuration. See easyXDM.Socket for more.
* @return {Array} An array of stack-elements with the TransportElement at index 0.
*/
function prepareTransportStack(config){
var protocol = config.protocol, stackEls;
config.isHost = config.isHost || undef(query.xdm_p);
useHash = config.hash || false;
if (!config.props) {
config.props = {};
}
if (!config.isHost) {
config.channel = query.xdm_c;
config.secret = query.xdm_s;
config.remote = query.xdm_e;
protocol = query.xdm_p;
if (config.acl && !checkAcl(config.acl, config.remote)) {
throw new Error("Access denied for " + config.remote);
}
}
else {
config.remote = resolveUrl(config.remote);
config.channel = config.channel || "default" + channelId++;
config.secret = Math.random().toString(16).substring(2);
if (undef(protocol)) {
if (getLocation(location.href) == getLocation(config.remote)) {
/*
* Both documents has the same origin, lets use direct access.
*/
protocol = "4";
}
else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) {
/*
* This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+
*/
protocol = "1";
}
else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) {
/*
* The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS
*/
protocol = "6";
}
else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) {
/*
* This is supported in Gecko (Firefox 1+)
*/
protocol = "5";
}
else if (config.remoteHelper) {
/*
* This is supported in all browsers that retains the value of window.name when
* navigating from one domain to another, and where parent.frames[foo] can be used
* to get access to a frame from the same domain
*/
config.remoteHelper = resolveUrl(config.remoteHelper);
protocol = "2";
}
else {
/*
* This is supported in all browsers where [window].location is writable for all
* The resize event will be used if resize is supported and the iframe is not put
* into a container, else polling will be used.
*/
protocol = "0";
}
}
}
config.protocol = protocol; // for conditional branching
switch (protocol) {
case "0":// 0 = HashTransport
apply(config, {
interval: 100,
delay: 2000,
useResize: true,
useParent: false,
usePolling: false
}, true);
if (config.isHost) {
if (!config.local) {
// If no local is set then we need to find an image hosted on the current domain
var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image;
var i = images.length;
while (i--) {
image = images[i];
if (image.src.substring(0, domain.length) === domain) {
config.local = image.src;
break;
}
}
if (!config.local) {
// If no local was set, and we are unable to find a suitable file, then we resort to using the current window
config.local = window;
}
}
var parameters = {
xdm_c: config.channel,
xdm_p: 0
};
if (config.local === window) {
// We are using the current window to listen to
config.usePolling = true;
config.useParent = true;
config.local = location.protocol + "//" + location.host + location.pathname + location.search;
parameters.xdm_e = config.local;
parameters.xdm_pa = 1; // use parent
}
else {
parameters.xdm_e = resolveUrl(config.local);
}
if (config.container) {
config.useResize = false;
parameters.xdm_po = 1; // use polling
}
config.remote = appendQueryParameters(config.remote, parameters);
}
else {
apply(config, {
channel: query.xdm_c,
remote: query.xdm_e,
useParent: !undef(query.xdm_pa),
usePolling: !undef(query.xdm_po),
useResize: config.useParent ? false : config.useResize
});
}
stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({
encode: true,
maxLength: 4000 - config.remote.length
}), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "1":
stackEls = [new easyXDM.stack.PostMessageTransport(config)];
break;
case "2":
stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "3":
stackEls = [new easyXDM.stack.NixTransport(config)];
break;
case "4":
stackEls = [new easyXDM.stack.SameOriginTransport(config)];
break;
case "5":
stackEls = [new easyXDM.stack.FrameElementTransport(config)];
break;
case "6":
if (!flashVersion) {
hasFlash();
}
stackEls = [new easyXDM.stack.FlashTransport(config)];
break;
}
// this behavior is responsible for buffering outgoing messages, and for performing lazy initialization
stackEls.push(new easyXDM.stack.QueueBehavior({
lazy: config.lazy,
remove: true
}));
return stackEls;
}
/**
* Chains all the separate stack elements into a single usable stack.<br/>
* If an element is missing a necessary method then it will have a pass-through method applied.
* @param {Array} stackElements An array of stack elements to be linked.
* @return {easyXDM.stack.StackElement} The last element in the chain.
*/
function chainStack(stackElements){
var stackEl, defaults = {
incoming: function(message, origin){
this.up.incoming(message, origin);
},
outgoing: function(message, recipient){
this.down.outgoing(message, recipient);
},
callback: function(success){
this.up.callback(success);
},
init: function(){
this.down.init();
},
destroy: function(){
this.down.destroy();
}
};
for (var i = 0, len = stackElements.length; i < len; i++) {
stackEl = stackElements[i];
apply(stackEl, defaults, true);
if (i !== 0) {
stackEl.down = stackElements[i - 1];
}
if (i !== len - 1) {
stackEl.up = stackElements[i + 1];
}
}
return stackEl;
}
/**
* This will remove a stackelement from its stack while leaving the stack functional.
* @param {Object} element The elment to remove from the stack.
*/
function removeFromStack(element){
element.up.down = element.down;
element.down.up = element.up;
element.up = element.down = null;
}
/*
* Export the main object and any other methods applicable
*/
/**
* @class easyXDM
* A javascript library providing cross-browser, cross-domain messaging/RPC.
* @version 2.4.15.118
* @singleton
*/
apply(easyXDM, {
/**
* The version of the library
* @type {string}
*/
version: "2.4.15.118",
/**
* This is a map containing all the query parameters passed to the document.
* All the values has been decoded using decodeURIComponent.
* @type {object}
*/
query: query,
/**
* @private
*/
stack: {},
/**
* Applies properties from the source object to the target object.<br/>
* @param {object} target The target of the properties.
* @param {object} source The source of the properties.
* @param {boolean} noOverwrite Set to True to only set non-existing properties.
*/
apply: apply,
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
getJSONObject: getJSON,
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {object} scope An optional scope for the function to be called with.
*/
whenReady: whenReady,
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
noConflict: noConflict
});
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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 evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.DomHelper
* Contains methods for dealing with the DOM
* @singleton
*/
easyXDM.DomHelper = {
/**
* Provides a consistent interface for adding eventhandlers
* @param {Object} target The target to add the event to
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
on: on,
/**
* Provides a consistent interface for removing eventhandlers
* @param {Object} target The target to remove the event from
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
un: un,
/**
* Checks for the presence of the JSON object.
* If it is not present it will use the supplied path to load the JSON2 library.
* This should be called in the documents head right after the easyXDM script tag.
* http://json.org/json2.js
* @param {String} path A valid path to json2.js
*/
requiresJSON: function(path){
if (!isHostObject(window, "JSON")) {
// we need to encode the < in order to avoid an illegal token error
// when the script is inlined in a document.
document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>');
}
}
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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(){
// The map containing the stored functions
var _map = {};
/**
* @class easyXDM.Fn
* This contains methods related to function handling, such as storing callbacks.
* @singleton
* @namespace easyXDM
*/
easyXDM.Fn = {
/**
* Stores a function using the given name for reference
* @param {String} name The name that the function should be referred by
* @param {Function} fn The function to store
* @namespace easyXDM.fn
*/
set: function(name, fn){
_map[name] = fn;
},
/**
* Retrieves the function referred to by the given name
* @param {String} name The name of the function to retrieve
* @param {Boolean} del If the function should be deleted after retrieval
* @return {Function} The stored function
* @namespace easyXDM.fn
*/
get: function(name, del){
var fn = _map[name];
if (del) {
delete _map[name];
}
return fn;
}
};
}());
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Socket
* This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/>
* The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/>
* Internally different stacks will be used depending on the browsers features and the available parameters.
* <h2>How to set up</h2>
* Setting up the provider:
* <pre><code>
* var socket = new easyXDM.Socket({
* local: "name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* Setting up the consumer:
* <pre><code>
* var socket = new easyXDM.Socket({
* remote: "http://remotedomain/page.html",
* remoteHelper: "http://remotedomain/name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property
* and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports.
* @namespace easyXDM
* @constructor
* @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window.
* @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed.
* @cfg {String} remote (Consumer only) The url to the providers document.
* @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000.
* @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300.
* @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional.
* @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional.
* @cfg {Function} onReady A method that should be called when the transport is ready. Optional.
* @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional.
* @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/>
* This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $.
* If none of the patterns match an Error will be thrown.
* @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>.
* Properties such as 'name' and 'src' will be overrided. Optional.
*/
easyXDM.Socket = function(config){
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([{
incoming: function(message, origin){
config.onMessage(message, origin);
},
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}])), recipient = getLocation(config.remote);
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
/**
* Posts a message to the remote end of the channel
* @param {String} message The message to send
*/
this.postMessage = function(message){
stack.outgoing(message, recipient);
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Rpc
* Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation
* of methods to be called from the remote end.<br/>
* The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/>
* This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods.
* <h2>How to set up</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* // this configuration is equal to that used by the Socket.
* remote: "http://remotedomain/...",
* onReady: function(){
* // you need to wait for the onReady callback before using the proxy
* rpc.foo(...
* }
* },{
* local: {..},
* remote: {..}
* });
* </code></pre>
*
* <h2>Exposing functions (procedures)</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {
* nameOfMethod: {
* method: function(arg1, arg2, success, error){
* ...
* }
* },
* // with shorthand notation
* nameOfAnotherMethod: function(arg1, arg2, success, error){
* }
* },
* remote: {...}
* });
* </code></pre>
* The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/>
* To send a successfull result back you can use
* <pre><code>
* return foo;
* </pre></code>
* or
* <pre><code>
* success(foo);
* </pre></code>
* To return an error you can use
* <pre><code>
* throw new Error("foo error");
* </code></pre>
* or
* <pre><code>
* error("foo error");
* </code></pre>
*
* <h2>Defining remotely exposed methods (procedures/notifications)</h2>
* The definition of the remote end is quite similar:
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {
* nameOfMethod: {}
* }
* });
* </code></pre>
* To call a remote method use
* <pre><code>
* rpc.nameOfMethod("arg1", "arg2", function(value) {
* alert("success: " + value);
* }, function(message) {
* alert("error: " + message + );
* });
* </code></pre>
* Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/>
* When called with no callback a JSON-RPC 2.0 notification will be executed.
* Be aware that you will not be notified of any errors with this method.
* <br/>
* <h2>Specifying a custom serializer</h2>
* If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library
* then you can specify a custom serializer using <code>serializer: foo</code>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {...},
* serializer : {
* parse: function(string){ ... },
* stringify: function(object) {...}
* }
* });
* </code></pre>
* If <code>serializer</code> is set then the class will not attempt to use the native implementation.
* @namespace easyXDM
* @constructor
* @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters.
* @param {Object} jsonRpcConfig The description of the interface to implement.
*/
easyXDM.Rpc = function(config, jsonRpcConfig){
// expand shorthand notation
if (jsonRpcConfig.local) {
for (var method in jsonRpcConfig.local) {
if (jsonRpcConfig.local.hasOwnProperty(method)) {
var member = jsonRpcConfig.local[method];
if (typeof member === "function") {
jsonRpcConfig.local[method] = {
method: member
};
}
}
}
}
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), {
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}]));
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.SameOriginTransport
* SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/>
* This can be useful for testing and for when the main application supports both internal and external sources.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.SameOriginTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send(message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: location.protocol + "//" + location.host + location.pathname,
xdm_c: config.channel,
xdm_p: 4 // 4 = SameOriginTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
easyXDM.Fn.set(config.channel, function(sendFn){
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
});
}
else {
send = getParentObject().Fn.get(config.channel, true)(function(msg){
pub.up.incoming(msg, targetOrigin);
});
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FlashTransport
* FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
* @cfg {String} secret the pre-shared secret used to secure the communication.
* @cfg {String} swf The path to the swf file
* @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden.
* @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed
*/
easyXDM.stack.FlashTransport = function(config){
var pub, // the public interface
frame, send, targetOrigin, swf, swfContainer;
function onMessage(message, origin){
setTimeout(function(){
pub.up.incoming(message, targetOrigin);
}, 0);
}
/**
* This method adds the SWF to the DOM and prepares the initialization of the channel
*/
function addSwf(domain){
// the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.
var url = config.swf + "?host=" + config.isHost;
var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
// prepare the init function that will fire once the swf is ready
easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){
easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;
var queue = easyXDM.stack.FlashTransport[domain].queue;
for (var i = 0; i < queue.length; i++) {
queue[i]();
}
queue.length = 0;
});
if (config.swfContainer) {
swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer;
}
else {
// create the container that will hold the swf
swfContainer = document.createElement('div');
// http://bugs.adobe.com/jira/browse/FP-4796
// http://tech.groups.yahoo.com/group/flexcoders/message/162365
// https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc
apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {
height: "20px",
width: "20px",
position: "fixed",
right: 0,
top: 0
} : {
height: "1px",
width: "1px",
position: "absolute",
overflow: "hidden",
right: 0,
top: 0
});
document.body.appendChild(swfContainer);
}
// create the object/embed
var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace;
swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" +
"<param name='allowScriptAccess' value='always'></param>" +
"<param name='wmode' value='transparent'>" +
"<param name='movie' value='" +
url +
"'></param>" +
"<param name='flashvars' value='" +
flashVars +
"'></param>" +
"<embed type='application/x-shockwave-flash' FlashVars='" +
flashVars +
"' allowScriptAccess='always' wmode='transparent' src='" +
url +
"' height='1' width='1'></embed>" +
"</object>";
}
return (pub = {
outgoing: function(message, domain, fn){
swf.postMessage(config.channel, message.toString());
if (fn) {
fn();
}
},
destroy: function(){
try {
swf.destroyChannel(config.channel);
}
catch (e) {
}
swf = null;
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = config.remote;
// Prepare the code that will be run after the swf has been intialized
easyXDM.Fn.set("flash_" + config.channel + "_init", function(){
setTimeout(function(){
pub.up.callback(true);
});
});
// set up the omMessage handler
easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths
var swfdomain = getDomainName(config.swf);
var fn = function(){
// set init to true in case the fn was called was invoked from a separate instance
easyXDM.stack.FlashTransport[swfdomain].init = true;
swf = easyXDM.stack.FlashTransport[swfdomain].swf;
// create the channel
swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost);
if (config.isHost) {
// if Flash is going to be throttled and we want to avoid this
if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) {
apply(config.props, {
position: "fixed",
right: 0,
top: 0,
height: "20px",
width: "20px"
});
}
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 6, // 6 = FlashTransport
xdm_s: config.secret
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
};
if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) {
// if the swf is in place and we are the consumer
fn();
}
else {
// if the swf does not yet exist
if (!easyXDM.stack.FlashTransport[swfdomain]) {
// add the queue to hold the init fn's
easyXDM.stack.FlashTransport[swfdomain] = {
queue: [fn]
};
addSwf(swfdomain);
}
else {
easyXDM.stack.FlashTransport[swfdomain].queue.push(fn);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.PostMessageTransport
* PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/>
* <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
*/
easyXDM.stack.PostMessageTransport = function(config){
var pub, // the public interface
frame, // the remote frame, if any
callerWindow, // the window that we will call with
targetOrigin; // the domain to communicate with
/**
* Resolves the origin from the event object
* @private
* @param {Object} event The messageevent
* @return {String} The scheme, host and port of the origin
*/
function _getOrigin(event){
if (event.origin) {
// This is the HTML5 property
return getLocation(event.origin);
}
if (event.uri) {
// From earlier implementations
return getLocation(event.uri);
}
if (event.domain) {
// This is the last option and will fail if the
// origin is not using the same schema as we are
return location.protocol + "//" + event.domain;
}
throw "Unable to retrieve the origin of the event";
}
/**
* This is the main implementation for the onMessage event.<br/>
* It checks the validity of the origin and passes the message on if appropriate.
* @private
* @param {Object} event The messageevent
*/
function _window_onMessage(event){
var origin = _getOrigin(event);
if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") {
pub.up.incoming(event.data.substring(config.channel.length + 1), origin);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin);
if (fn) {
fn();
}
},
destroy: function(){
un(window, "message", _window_onMessage);
if (frame) {
callerWindow = null;
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// add the event handler for listening
var waitForReady = function(event){
if (event.data == config.channel + "-ready") {
// replace the eventlistener
callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document;
un(window, "message", waitForReady);
on(window, "message", _window_onMessage);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
};
on(window, "message", waitForReady);
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 1 // 1 = PostMessage
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
else {
// add the event handler for listening
on(window, "message", _window_onMessage);
callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document;
callerWindow.postMessage(config.channel + "-ready", targetOrigin);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FrameElementTransport
* FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/>
* Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.FrameElementTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send.call(this, message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 5 // 5 = FrameElementTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
frame.fn = function(sendFn){
delete frame.fn;
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
// remove the function so that it cannot be used to overwrite the send function later on
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
};
}
else {
// This is to mitigate origin-spoofing
if (document.referrer && getLocation(document.referrer) != query.xdm_e) {
window.top.location = query.xdm_e;
}
send = window.frameElement.fn(function(msg){
pub.up.incoming(msg, targetOrigin);
});
pub.up.callback(true);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.NameTransport
* NameTransport uses the window.name property to relay data.
* The <code>local</code> parameter needs to be set on both the consumer and provider,<br/>
* and the <code>remoteHelper</code> parameter needs to be set on the consumer.
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host.
* @namespace easyXDM.stack
*/
easyXDM.stack.NameTransport = function(config){
var pub; // the public interface
var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl;
function _sendMessage(message){
var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel;
callerWindow.contentWindow.sendMessage(message, url);
}
function _onReady(){
if (isHost) {
if (++readyCount === 2 || !isHost) {
pub.up.callback(true);
}
}
else {
_sendMessage("ready");
pub.up.callback(true);
}
}
function _onMessage(message){
pub.up.incoming(message, remoteOrigin);
}
function _onLoad(){
if (callback) {
setTimeout(function(){
callback(true);
}, 0);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callback = fn;
_sendMessage(message);
},
destroy: function(){
callerWindow.parentNode.removeChild(callerWindow);
callerWindow = null;
if (isHost) {
remoteWindow.parentNode.removeChild(remoteWindow);
remoteWindow = null;
}
},
onDOMReady: function(){
isHost = config.isHost;
readyCount = 0;
remoteOrigin = getLocation(config.remote);
config.local = resolveUrl(config.local);
if (isHost) {
// Register the callback
easyXDM.Fn.set(config.channel, function(message){
if (isHost && message === "ready") {
// Replace the handler
easyXDM.Fn.set(config.channel, _onMessage);
_onReady();
}
});
// Set up the frame that points to the remote instance
remoteUrl = appendQueryParameters(config.remote, {
xdm_e: config.local,
xdm_c: config.channel,
xdm_p: 2
});
apply(config.props, {
src: remoteUrl + '#' + config.channel,
name: IFRAME_PREFIX + config.channel + "_provider"
});
remoteWindow = createFrame(config);
}
else {
config.remoteHelper = config.remote;
easyXDM.Fn.set(config.channel, _onMessage);
}
// Set up the iframe that will be used for the transport
callerWindow = createFrame({
props: {
src: config.local + "#_4" + config.channel
},
onLoad: function onLoad(){
// Remove the handler
var w = callerWindow || this;
un(w, "load", onLoad);
easyXDM.Fn.set(config.channel + "_load", _onLoad);
(function test(){
if (typeof w.contentWindow.sendMessage == "function") {
_onReady();
}
else {
setTimeout(test, 50);
}
}());
}
});
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.HashTransport
* HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
* @cfg {Number} interval The interval used when polling for messages.
*/
easyXDM.stack.HashTransport = function(config){
var pub;
var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
var useParent, _remoteOrigin;
function _sendMessage(message){
if (!_callerWindow) {
return;
}
var url = config.remote + "#" + (_msgNr++) + "_" + message;
((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url;
}
function _handleHash(hash){
_lastMsg = hash;
pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
}
/**
* Checks location.hash for a new message and relays this to the receiver.
* @private
*/
function _pollHash(){
if (!_listenerWindow) {
return;
}
var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#");
if (indexOf != -1) {
hash = href.substring(indexOf);
}
if (hash && hash != _lastMsg) {
_handleHash(hash);
}
}
function _attachListeners(){
_timer = setInterval(_pollHash, pollInterval);
}
return (pub = {
outgoing: function(message, domain){
_sendMessage(message);
},
destroy: function(){
window.clearInterval(_timer);
if (isHost || !useParent) {
_callerWindow.parentNode.removeChild(_callerWindow);
}
_callerWindow = null;
},
onDOMReady: function(){
isHost = config.isHost;
pollInterval = config.interval;
_lastMsg = "#" + config.channel;
_msgNr = 0;
useParent = config.useParent;
_remoteOrigin = getLocation(config.remote);
if (isHost) {
config.props = {
src: config.remote,
name: IFRAME_PREFIX + config.channel + "_provider"
};
if (useParent) {
config.onLoad = function(){
_listenerWindow = window;
_attachListeners();
pub.up.callback(true);
};
}
else {
var tries = 0, max = config.delay / 50;
(function getRef(){
if (++tries > max) {
throw new Error("Unable to reference listenerwindow");
}
try {
_listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"];
}
catch (ex) {
}
if (_listenerWindow) {
_attachListeners();
pub.up.callback(true);
}
else {
setTimeout(getRef, 50);
}
}());
}
_callerWindow = createFrame(config);
}
else {
_listenerWindow = window;
_attachListeners();
if (useParent) {
_callerWindow = parent;
pub.up.callback(true);
}
else {
apply(config, {
props: {
src: config.remote + "#" + config.channel + new Date(),
name: IFRAME_PREFIX + config.channel + "_consumer"
},
onLoad: function(){
pub.up.callback(true);
}
});
_callerWindow = createFrame(config);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.ReliableBehavior
* This is a behavior that tries to make the underlying transport reliable by using acknowledgements.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
*/
easyXDM.stack.ReliableBehavior = function(config){
var pub, // the public interface
callback; // the callback to execute when we have a confirmed success/failure
var idOut = 0, idIn = 0, currentMessage = "";
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(",");
message = message.substring(indexOf + 1);
if (ack[0] == idOut) {
currentMessage = "";
if (callback) {
callback(true);
}
}
if (message.length > 0) {
pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin);
if (idIn != ack[1]) {
idIn = ack[1];
pub.up.incoming(message, origin);
}
}
},
outgoing: function(message, origin, fn){
currentMessage = message;
callback = fn;
pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.QueueBehavior
* This is a behavior that enables queueing of messages. <br/>
* It will buffer incoming messages and dispach these as fast as the underlying transport allows.
* This will also fragment/defragment messages so that the outgoing message is never bigger than the
* set length.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration. Optional.
* @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation.
*/
easyXDM.stack.QueueBehavior = function(config){
var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false;
function dispatch(){
if (config.remove && queue.length === 0) {
removeFromStack(pub);
return;
}
if (waiting || queue.length === 0 || destroying) {
return;
}
waiting = true;
var message = queue.shift();
pub.down.outgoing(message.data, message.origin, function(success){
waiting = false;
if (message.callback) {
setTimeout(function(){
message.callback(success);
}, 0);
}
dispatch();
});
}
return (pub = {
init: function(){
if (undef(config)) {
config = {};
}
if (config.maxLength) {
maxLength = config.maxLength;
doFragment = true;
}
if (config.lazy) {
lazy = true;
}
else {
pub.down.init();
}
},
callback: function(success){
waiting = false;
var up = pub.up; // in case dispatch calls removeFromStack
dispatch();
up.callback(success);
},
incoming: function(message, origin){
if (doFragment) {
var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10);
incoming += message.substring(indexOf + 1);
if (seq === 0) {
if (config.encode) {
incoming = decodeURIComponent(incoming);
}
pub.up.incoming(incoming, origin);
incoming = "";
}
}
else {
pub.up.incoming(message, origin);
}
},
outgoing: function(message, origin, fn){
if (config.encode) {
message = encodeURIComponent(message);
}
var fragments = [], fragment;
if (doFragment) {
// fragment into chunks
while (message.length !== 0) {
fragment = message.substring(0, maxLength);
message = message.substring(fragment.length);
fragments.push(fragment);
}
// enqueue the chunks
while ((fragment = fragments.shift())) {
queue.push({
data: fragments.length + "_" + fragment,
origin: origin,
callback: fragments.length === 0 ? fn : null
});
}
}
else {
queue.push({
data: message,
origin: origin,
callback: fn
});
}
if (lazy) {
pub.down.init();
}
else {
dispatch();
}
},
destroy: function(){
destroying = true;
pub.down.destroy();
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.VerifyBehavior
* This behavior will verify that communication with the remote end is possible, and will also sign all outgoing,
* and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
* @cfg {Boolean} initiate If the verification should be initiated from this end.
*/
easyXDM.stack.VerifyBehavior = function(config){
var pub, mySecret, theirSecret, verified = false;
function startVerification(){
mySecret = Math.random().toString(16).substring(2);
pub.down.outgoing(mySecret);
}
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_");
if (indexOf === -1) {
if (message === mySecret) {
pub.up.callback(true);
}
else if (!theirSecret) {
theirSecret = message;
if (!config.initiate) {
startVerification();
}
pub.down.outgoing(message);
}
}
else {
if (message.substring(0, indexOf) === theirSecret) {
pub.up.incoming(message.substring(indexOf + 1), origin);
}
}
},
outgoing: function(message, origin, fn){
pub.down.outgoing(mySecret + "_" + message, origin, fn);
},
callback: function(success){
if (config.initiate) {
startVerification();
}
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.RpcBehavior
* This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/>
* Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything.
* @namespace easyXDM.stack
* @constructor
* @param {Object} proxy The object to apply the methods to.
* @param {Object} config The definition of the local and remote interface to implement.
* @cfg {Object} local The local interface to expose.
* @cfg {Object} remote The remote methods to expose through the proxy.
* @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON.
*/
easyXDM.stack.RpcBehavior = function(proxy, config){
var pub, serializer = config.serializer || getJSON();
var _callbackCounter = 0, _callbacks = {};
/**
* Serializes and sends the message
* @private
* @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added.
*/
function _send(data){
data.jsonrpc = "2.0";
pub.down.outgoing(serializer.stringify(data));
}
/**
* Creates a method that implements the given definition
* @private
* @param {Object} The method configuration
* @param {String} method The name of the method
* @return {Function} A stub capable of proxying the requested method call
*/
function _createMethod(definition, method){
var slice = Array.prototype.slice;
return function(){
var l = arguments.length, callback, message = {
method: method
};
if (l > 0 && typeof arguments[l - 1] === "function") {
//with callback, procedure
if (l > 1 && typeof arguments[l - 2] === "function") {
// two callbacks, success and error
callback = {
success: arguments[l - 2],
error: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 2);
}
else {
// single callback, success
callback = {
success: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 1);
}
_callbacks["" + (++_callbackCounter)] = callback;
message.id = _callbackCounter;
}
else {
// no callbacks, a notification
message.params = slice.call(arguments, 0);
}
if (definition.namedParams && message.params.length === 1) {
message.params = message.params[0];
}
// Send the method request
_send(message);
};
}
/**
* Executes the exposed method
* @private
* @param {String} method The name of the method
* @param {Number} id The callback id to use
* @param {Function} method The exposed implementation
* @param {Array} params The parameters supplied by the remote end
*/
function _executeMethod(method, id, fn, params){
if (!fn) {
if (id) {
_send({
id: id,
error: {
code: -32601,
message: "Procedure not found."
}
});
}
return;
}
var success, error;
if (id) {
success = function(result){
success = emptyFn;
_send({
id: id,
result: result
});
};
error = function(message, data){
error = emptyFn;
var msg = {
id: id,
error: {
code: -32099,
message: message
}
};
if (data) {
msg.error.data = data;
}
_send(msg);
};
}
else {
success = error = emptyFn;
}
// Call local method
if (!isArray(params)) {
params = [params];
}
try {
var result = fn.method.apply(fn.scope, params.concat([success, error]));
if (!undef(result)) {
success(result);
}
}
catch (ex1) {
error(ex1.message);
}
}
return (pub = {
incoming: function(message, origin){
var data = serializer.parse(message);
if (data.method) {
// A method call from the remote end
if (config.handle) {
config.handle(data, _send);
}
else {
_executeMethod(data.method, data.id, config.local[data.method], data.params);
}
}
else {
// A method response from the other end
var callback = _callbacks[data.id];
if (data.error) {
if (callback.error) {
callback.error(data.error);
}
}
else if (callback.success) {
callback.success(data.result);
}
delete _callbacks[data.id];
}
},
init: function(){
if (config.remote) {
// Implement the remote sides exposed methods
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method)) {
proxy[method] = _createMethod(config.remote[method], method);
}
}
}
pub.down.init();
},
destroy: function(){
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
delete proxy[method];
}
}
pub.down.destroy();
}
});
};
global.easyXDM = easyXDM;
})(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent);
/*!
* F2 v1.3.0 09-16-2013
* Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org
*
* "F2" is 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.
*
* Please note that F2 ("Software") may contain third party material that Markit
* On Demand Inc. has a license to use and include within the Software (the
* "Third Party Material"). A list of the software comprising the Third Party Material
* and the terms and conditions under which such Third Party Material is distributed
* are reproduced in the ThirdPartyMaterial.md file available at:
*
* https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md
*
* The inclusion of the Third Party Material in the Software does not grant, provide
* nor result in you having acquiring any rights whatsoever, other than as stipulated
* in the terms and conditions related to the specific Third Party Material, if any.
*
*/
var F2;
/**
* Open F2
* @module f2
* @main f2
*/
F2 = (function() {
/**
* Abosolutizes a relative URL
* @method _absolutizeURI
* @private
* @param {e.g., location.href} base
* @param {URL to absolutize} href
* @returns {string} URL
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _absolutizeURI = function(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
href = _parseURI(href || '');
base = _parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
};
/**
* Parses URI
* @method _parseURI
* @private
* @param {The URL to parse} url
* @returns {Parsed URL} string
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _parseURI = function(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
};
return {
/**
* A function to pass into F2.stringify which will prevent circular
* reference errors when serializing objects
* @method appConfigReplacer
*/
appConfigReplacer: function(key, value) {
if (key == 'root' || key == 'ui' || key == 'height') {
return undefined;
} else {
return value;
}
},
/**
* The apps namespace is a place for app developers to put the javascript
* class that is used to initialize their app. The javascript classes should
* be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId.
* It is recommended that the code be placed in a closure to help keep the
* global namespace clean.
*
* If the class has an 'init' function, that function will be called
* automatically by F2.
* @property Apps
* @type object
* @example
* F2.Apps["com_example_helloworld"] = (function() {
* var App_Class = function(appConfig, appContent, root) {
* this._app = appConfig; // the F2.AppConfig object
* this._appContent = appContent // the F2.AppManifest.AppContent object
* this.$root = $(root); // the root DOM Element that contains this app
* }
*
* App_Class.prototype.init = function() {
* // perform init actions
* }
*
* return App_Class;
* })();
* @example
* F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) {
* return {
* init:function() {
* // perform init actions
* }
* };
* };
* @for F2
*/
Apps: {},
/**
* Creates a namespace on F2 and copies the contents of an object into
* that namespace optionally overwriting existing properties.
* @method extend
* @param {string} ns The namespace to create. Pass a falsy value to
* add properties to the F2 namespace directly.
* @param {object} obj The object to copy into the namespace.
* @param {bool} overwrite True if object properties should be overwritten
* @return {object} The created object
*/
extend: function (ns, obj, overwrite) {
var isFunc = typeof obj === 'function';
var parts = ns ? ns.split('.') : [];
var parent = this;
obj = obj || {};
// ignore leading global
if (parts[0] === 'F2') {
parts = parts.slice(1);
}
// create namespaces
for (var i = 0, len = parts.length; i < len; i++) {
if (!parent[parts[i]]) {
parent[parts[i]] = isFunc && i + 1 == len ? obj : {};
}
parent = parent[parts[i]];
}
// copy object into namespace
if (!isFunc) {
for (var prop in obj) {
if (typeof parent[prop] === 'undefined' || overwrite) {
parent[prop] = obj[prop];
}
}
}
return parent;
},
/**
* Generates a somewhat random id
* @method guid
* @return {string} A random id
* @for F2
*/
guid: function() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4());
},
/**
* Search for a value within an array.
* @method inArray
* @param {object} value The value to search for
* @param {Array} array The array to search
* @return {bool} True if the item is in the array
*/
inArray: function(value, array) {
return jQuery.inArray(value, array) > -1;
},
/**
* Tests a URL to see if it's on the same domain (local) or not
* @method isLocalRequest
* @param {URL to test} url
* @returns {bool} Whether the URL is local or not
* Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js
*/
isLocalRequest: function(url){
var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
urlLower = url.toLowerCase(),
parts = rurl.exec( urlLower ),
ajaxLocation,
ajaxLocParts;
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;
}
ajaxLocation = ajaxLocation.toLowerCase();
// uh oh, the url must be relative
// make it fully qualified and re-regex url
if (!parts){
urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase();
parts = rurl.exec( urlLower );
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation ) || [];
// do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain)
var matched = !(parts &&
(parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
(parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !==
(ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443'))));
return matched;
},
/**
* Utility method to determine whether or not the argument passed in is or is not a native dom node.
* @method isNativeDOMNode
* @param {object} testObject The object you want to check as native dom node.
* @return {bool} Returns true if the object passed is a native dom node.
*/
isNativeDOMNode: function(testObject) {
var bIsNode = (
typeof Node === 'object' ? testObject instanceof Node :
testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string'
);
var bIsElement = (
typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2
testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string'
);
return (bIsNode || bIsElement);
},
/**
* A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console).
* @method log
* @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api).
* @param {object} [obj2]* An object to be logged
* @example
//Pass any object (string, int, array, object, bool) to .log()
F2.log('foo');
F2.log(myArray);
//Use a console method name as the first argument.
F2.log('error', err);
F2.log('info', 'The session ID is ' + sessionId);
* Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js)
*/
log: function() {
var _log;
var _logMethod = 'log';
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
var args;
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
//if first arg is a console function, use it.
//defaults to console.log()
if (arguments && arguments.length > 1 && arguments[0] == method){
_logMethod = method;
//remove console func from args
args = Array.prototype.slice.call(arguments, 1);
}
}
if (Function.prototype.bind) {
_log = Function.prototype.bind.call(console[_logMethod], console);
} else {
_log = function() {
Function.prototype.apply.call(console[_logMethod], console, (args || arguments));
};
}
_log.apply(this, (args || arguments));
},
/**
* Wrapper to convert a JSON string to an object
* @method parse
* @param {string} str The JSON string to convert
* @return {object} The parsed object
*/
parse: function(str) {
return JSON.parse(str);
},
/**
* Wrapper to convert an object to JSON
*
* **Note: When using F2.stringify on an F2.AppConfig object, it is
* recommended to pass F2.appConfigReplacer as the replacer function in
* order to prevent circular serialization errors.**
* @method stringify
* @param {object} value The object to convert
* @param {function|Array} replacer An optional parameter that determines
* how object values are stringified for objects. It can be a function or an
* array of strings.
* @param {int|string} space An optional parameter that specifies the
* indentation of nested structures. If it is omitted, the text will be
* packed without extra whitespace. If it is a number, it will specify the
* number of spaces to indent at each level. If it is a string (such as '\t'
* or ' '), it contains the characters used to indent at each level.
* @return {string} The JSON string
*/
stringify: function(value, replacer, space) {
return JSON.stringify(value, replacer, space);
},
/**
* Function to get the F2 version number
* @method version
* @return {string} F2 version number
*/
version: function() { return '{{sdk.version}}'; }
};
})();
/**
* The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction.
*
*<p class="alert alert-block alert-warning">
*The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated—but not removed—in version 1.2. They will be permanently removed in a future version of F2.
*</p>
*
*<p class="alert alert-block alert-info">
*Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout.
*</p>
*
* ### Order of Execution
*
* **App Rendering**
*
* 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed.
* 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached.
* 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached.
* 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired.
* 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached.
* 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached.
*
*
* **App Removal**
* 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run.
* 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached.
* 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached.
* 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached.
* @class F2.AppHandlers
*/
F2.extend('AppHandlers', (function() {
// the hidden token that we will check against every time someone tries to add, remove, fire handler
var _ct = F2.guid();
var _f2t = F2.guid();
var _handlerCollection = {
appCreateRoot: [],
appRenderBefore: [],
appDestroyBefore: [],
appRenderAfter: [],
appDestroyAfter: [],
appRender: [],
appDestroy: []
};
var _defaultMethods = {
appRender: function(appConfig, appHtml)
{
var $root = null;
// if no app root is defined use the app's outer most node
if(!F2.isNativeDOMNode(appConfig.root))
{
appConfig.root = jQuery(appHtml).get(0);
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
}
else
{
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
// append the app html to the root
$root.append(appHtml);
}
// append the root to the body by default.
jQuery('body').append($root);
},
appDestroy: function(appInstance)
{
// call the apps destroy method, if it has one
if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
{
appInstance.app.destroy();
}
// warn the Container and App Developer that even though they have a destroy method it hasn't been
else if(appInstance && appInstance.app && appInstance.app.destroy)
{
F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
}
// fade out and remove the root
jQuery(appInstance.config.root).fadeOut(500, function() {
jQuery(this).remove();
});
}
};
var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(token);
// create handler structure. Not all arguments properties will be populated/used.
var handler = {
func: (typeof(func_or_element)) ? func_or_element : null,
namespace: sNamespace,
domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null
};
if(!handler.func && !handler.domNode)
{
throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.');
}
if(handler.domNode && !bDomNodeAppropriate)
{
throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.');
}
return handler;
};
var _validateToken = function(sToken)
{
// check token against F2 and container
if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); }
};
var _removeHandler = function(sToken, eventKey, sNamespace)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(sToken);
if(!sNamespace && !eventKey)
{
return;
}
// remove by event key
else if(!sNamespace && eventKey)
{
_handlerCollection[eventKey] = [];
}
// remove by namespace only
else if(sNamespace && !eventKey)
{
sNamespace = sNamespace.toLowerCase();
for(var currentEventKey in _handlerCollection)
{
var eventCollection = _handlerCollection[currentEventKey];
var newEvents = [];
for(var i = 0, ec = eventCollection.length; i < ec; i++)
{
var currentEventHandler = eventCollection[i];
if(currentEventHandler)
{
if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace)
{
newEvents.push(currentEventHandler);
}
}
}
eventCollection = newEvents;
}
}
else if(sNamespace && _handlerCollection[eventKey])
{
sNamespace = sNamespace.toLowerCase();
var newHandlerCollection = [];
for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++)
{
var currentHandler = _handlerCollection[eventKey][iCounter];
if(currentHandler)
{
if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace)
{
newHandlerCollection.push(currentHandler);
}
}
}
_handlerCollection[eventKey] = newHandlerCollection;
}
};
return {
/**
* Allows Container Developer to retrieve a unique token which must be passed to
* all `on` and `off` methods. This function will self destruct and can only be called
* one time. Container Developers must store the return value inside of a closure.
* @method getToken
**/
getToken: function()
{
// delete this method for security that way only the container has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.getToken;
// return the token, which we validate against.
return _ct;
},
/**
* Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}.
* This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}
* and additional internal methods.
* @method __f2GetToken
* @private
**/
__f2GetToken: function()
{
// delete this method for security that way only the F2 internally has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.__f2GetToken;
// return the token, which we validate against.
return _f2t;
},
/**
* Allows F2 to trigger specific events internally.
* @method __trigger
* @private
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}.
* @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
**/
__trigger: function(token, eventKey) // additional arguments will likely be passed
{
// will throw an exception and stop execution if the token is invalid
if(token != _f2t)
{
throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().');
}
if(_handlerCollection && _handlerCollection[eventKey])
{
// create a collection of arguments that are safe to pass to the callback.
var passableArgs = [];
// populate that collection with all arguments except token and eventKey
for(var i = 2, j = arguments.length; i < j; i++)
{
passableArgs.push(arguments[i]);
}
if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey])
{
_defaultMethods[eventKey].apply(F2, passableArgs);
return this;
}
else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey])
{
return this;
}
// fire all event listeners in the order that they were added.
for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++)
{
var handler = _handlerCollection[eventKey][iCounter];
// appRender where root is already defined
if (handler.domNode && arguments[2] && arguments[2].root && arguments[3])
{
var $appRoot = jQuery(arguments[2].root).append(arguments[3]);
jQuery(handler.domNode).append($appRoot);
}
else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3])
{
// set the root to the actual HTML of the app
arguments[2].root = jQuery(arguments[3]).get(0);
// appends the root to the dom node specified
jQuery(handler.domNode).append(arguments[2].root);
}
else
{
handler.func.apply(F2, passableArgs);
}
}
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {HTMLElement} element Specific DOM element to which app gets appended.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRender',
* document.getElementById('my_app')
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRender.myNamespace',
* document.getElementById('my_app')
* );
**/
/**
* Allows Container Developer to add listener method that will be triggered when a specific event occurs.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore'
* function() { F2.log('before app rendered!'); }
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore.myNamespace',
* function() { F2.log('before app rendered!'); }
* );
**/
on: function(token, eventKey, func_or_element)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_handlerCollection[eventKey].push(
_createHandler(
token,
sNamespace,
func_or_element,
(eventKey == 'appRender')
)
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to remove listener methods for specific events
* @method off
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all
* listeners for the specified event type will be removed.
* Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.off(_token,'appRenderBefore');
*
**/
off: function(token, eventKey)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_removeHandler(
token,
eventKey,
sNamespace
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
}
};
})());
F2.extend('Constants', {
/**
* A convenient collection of all available appHandler events.
* @class F2.Constants.AppHandlers
**/
AppHandlers: (function()
{
return {
/**
* Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_CREATE_ROOT
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_CREATE_ROOT,
* function(appConfig)
* {
* // If you want to create a custom root. By default F2 uses the app's outermost HTML element.
* // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER
* appConfig.root = jQuery('<section></section>').get(0);
* }
* );
*/
APP_CREATE_ROOT: 'appCreateRoot',
/**
* Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_BEFORE,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_BEFORE: 'appRenderBefore',
/**
* Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) )
* @property APP_RENDER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER,
* function(appConfig, appHtml)
* {
* var $root = null;
*
* // if no app root is defined use the app's outer most node
* if(!F2.isNativeDOMNode(appConfig.root))
* {
* appConfig.root = jQuery(appHtml).get(0);
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
* }
* else
* {
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
*
* // append the app html to the root
* $root.append(appHtml);
* }
*
* // append the root to the body by default.
* jQuery('body').append($root);
* }
* );
*/
APP_RENDER: 'appRender',
/**
* Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_AFTER,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_AFTER: 'appRenderAfter',
/**
* Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_BEFORE: 'appDestroyBefore',
/**
* Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY,
* function(appInstance)
* {
* // call the apps destroy method, if it has one
* if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
* {
* appInstance.app.destroy();
* }
* else if(appInstance && appInstance.app && appInstance.app.destroy)
* {
* F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
* }
*
* // fade out and remove the root
* jQuery(appInstance.config.root).fadeOut(500, function() {
* jQuery(this).remove();
* });
* }
* );
*/
APP_DESTROY: 'appDestroy',
/**
* Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_AFTER,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_AFTER: 'appDestroyAfter'
};
})()
});
/**
* Class stubs for documentation purposes
* @main F2
*/
F2.extend('', {
/**
* The App Class is an optional class that can be namespaced onto the
* {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The
* [F2 Docs](../../app-development.html#app-class)
* has more information on the usage of the App Class.
* @class F2.App
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object for the app
* @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent
* object
* @param {Element} root The root DOM Element for the app
*/
App: function(appConfig, appContent, root) {
return {
/**
* An optional init function that will automatically be called when
* F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called.
* @method init
* @optional
*/
init:function() {}
};
},
/**
* The AppConfig object represents an app's meta data
* @class F2.AppConfig
*/
AppConfig: {
/**
* The unique ID of the app. More information can be found
* [here](../../app-development.html#f2-appid)
* @property appId
* @type string
* @required
*/
appId: '',
/**
* An object that represents the context of an app
* @property context
* @type object
*/
context: {},
/**
* True if the app should be requested in a single request with other apps.
* @property enableBatchRequests
* @type bool
* @default false
*/
enableBatchRequests: false,
/**
* The height of the app. The initial height will be pulled from
* the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later
* modified by calling
* F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used
* for secure apps to be able to set the initial height of the iframe.
* @property height
* @type int
*/
height: 0,
/**
* The unique runtime ID of the app.
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property instanceId
* @type string
*/
instanceId: '',
/**
* True if the app will be loaded in an iframe. This property
* will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object
* sets isSecure = true. It will also be true if the
* [container](../../container-development.html) has made the decision to
* run apps in iframes.
* @property isSecure
* @type bool
* @default false
*/
isSecure: false,
/**
* The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* object.
* @property manifestUrl
* @type string
* @required
*/
manifestUrl: '',
/**
* The recommended maximum width in pixels that this app should be run.
* **It is up to the [container](../../container-development.html) to
* implement the logic to prevent an app from being run when the maxWidth
* requirements are not met.**
* @property maxWidth
* @type int
*/
maxWidth: 0,
/**
* The recommended minimum grid size that this app should be run. This
* value corresponds to the 12-grid system that is used by the
* [container](../../container-development.html). This property should be
* set by apps that require a certain number of columns in their layout.
* @property minGridSize
* @type int
* @default 4
*/
minGridSize: 4,
/**
* The recommended minimum width in pixels that this app should be run. **It
* is up to the [container](../../container-development.html) to implement
* the logic to prevent an app from being run when the minWidth requirements
* are not met.
* @property minWidth
* @type int
* @default 300
*/
minWidth: 300,
/**
* The name of the app
* @property name
* @type string
* @required
*/
name: '',
/**
* The root DOM element that contains the app
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property root
* @type Element
*/
root: undefined,
/**
* The instance of F2.UI providing easy access to F2.UI methods
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property ui
* @type F2.UI
*/
ui: undefined,
/**
* The views that this app supports. Available views
* are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The
* presence of a view can be checked via
* F2.{{#crossLink "F2/inArray"}}{{/crossLink}}:
*
* F2.inArray(F2.Constants.Views.SETTINGS, app.views)
*
* @property views
* @type Array
*/
views: []
},
/**
* The assets needed to render an app on the page
* @class F2.AppManifest
*/
AppManifest: {
/**
* The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}}
* objects
* @property apps
* @type Array
* @required
*/
apps: [],
/**
* Any inline javascript tha should initially be run
* @property inlineScripts
* @type Array
* @optional
*/
inlineScripts: [],
/**
* Urls to javascript files required by the app
* @property scripts
* @type Array
* @optional
*/
scripts: [],
/**
* Urls to CSS files required by the app
* @property styles
* @type Array
* @optional
*/
styles: []
},
/**
* The AppContent object
* @class F2.AppManifest.AppContent
**/
AppContent: {
/**
* Arbitrary data to be passed along with the app
* @property data
* @type object
* @optional
*/
data: {},
/**
* The string of HTML representing the app
* @property html
* @type string
* @required
*/
html: '',
/**
* A status message
* @property status
* @type string
* @optional
*/
status: ''
},
/**
* An object containing configuration information for the
* [container](../../container-development.html)
* @class F2.ContainerConfig
*/
ContainerConfig: {
/**
* Allows the [container](../../container-development.html) to override how
* an app's html is inserted into the page. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html
* @method afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
* @return {Element} The DOM Element surrounding the app
*/
afterAppRender: function(appConfig, html) {},
/**
* Allows the [container](../../container-development.html) to wrap an app
* in extra html. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html. The extra html can provide links to edit app settings and remove an
* app from the container. See
* {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that
* should be applied to elements.
* @method appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
*/
appRender: function(appConfig, html) {},
/**
* Allows the container to render html for an app before the AppManifest for
* an app has loaded. This can be useful if the design calls for loading
* icons to appear for each app before each app is loaded and rendered to
* the page.
* @method beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
beforeAppRender: function(appConfig) {},
/**
* True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc.
* @property debugMode
* @type bool
* @default false
*/
debugMode: false,
/**
* Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire.
* @property scriptErrorTimeout
* @type milliseconds
* @default 7000 (7 seconds)
*/
scriptErrorTimeout: 7000,
/**
* Tells the container that it is currently running within
* a secure app page
* @property isSecureAppPage
* @type bool
*/
isSecureAppPage: false,
/**
* Allows the container to specify which page is used when
* loading a secure app. The page must reside on a different domain than the
* container
* @property secureAppPagePath
* @type string
* @for F2.ContainerConfig
*/
secureAppPagePath: '',
/**
* Specifies what views a container will provide buttons
* or links to. Generally, the views will be switched via buttons or links
* in the app's header.
* @property supportedViews
* @type Array
* @required
*/
supportedViews: [],
/**
* An object containing configuration defaults for F2.UI
* @class F2.ContainerConfig.UI
*/
UI: {
/**
* An object containing configuration defaults for the
* F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and
* F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods.
* @class F2.ContainerConfig.UI.Mask
*/
Mask: {
/**
* The backround color of the overlay
* @property backgroundColor
* @type string
* @default #FFF
*/
backgroundColor: '#FFF',
/**
* The path to the loading icon
* @property loadingIcon
* @type string
*/
loadingIcon: '',
/**
* The opacity of the background overlay
* @property opacity
* @type int
* @default 0.6
*/
opacity: 0.6,
/**
* Do not use inline styles for mask functinality. Instead classes will
* be applied to the elements and it is up to the container provider to
* implement the class definitions.
* @property useClasses
* @type bool
* @default false
*/
useClasses: false,
/**
* The z-index to use for the overlay
* @property zIndex
* @type int
* @default 2
*/
zIndex: 2
}
},
/**
* Allows the container to fully override how the AppManifest request is
* made inside of F2.
*
* @method xhr
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {function} success The function to be called if the request
* succeeds
* @param {function} error The function to be called if the request fails
* @param {function} complete The function to be called when the request
* finishes (after success and error callbacks have been executed)
* @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has
* an `abort` function (such as the jqXHR object in jQuery) to abort the
* request)
*
* @example
* F2.init({
* xhr: function(url, appConfigs, success, error, complete) {
* $.ajax({
* url: url,
* type: 'POST',
* data: {
* params: F2.stringify(appConfigs, F2.appConfigReplacer)
* },
* jsonp: false, // do not put 'callback=' in the query string
* jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name
* dataType: 'json',
* success: function(appManifest) {
* // custom success logic
* success(appManifest); // fire success callback
* },
* error: function() {
* // custom error logic
* error(); // fire error callback
* },
* complete: function() {
* // custom complete logic
* complete(); // fire complete callback
* }
* });
* }
* });
*
* @for F2.ContainerConfig
*/
//xhr: function(url, appConfigs, success, error, complete) {},
/**
* Allows the container to override individual parts of the AppManifest
* request. See properties and methods with the `xhr.` prefix.
* @property xhr
* @type Object
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
xhr: {
/**
* Allows the container to override the request data type (JSON or JSONP)
* that is used for the request
* @method xhr.dataType
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request data type that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
dataType: function(url, appConfigs) {},
/**
* Allows the container to override the request method that is used (just
* like the `type` parameter to `jQuery.ajax()`.
* @method xhr.type
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request method that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
type: function(url, appConfigs) {},
/**
* Allows the container to override the url that is used to request an
* app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}}
* @method xhr.url
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The url that should be used for the request
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
url: function(url, appConfigs) {}
}
}
});
/**
* Constants used throughout the Open Financial Framework
* @class F2.Constants
* @static
*/
F2.extend('Constants', {
/**
* CSS class constants
* @class F2.Constants.Css
*/
Css: (function() {
/** @private */
var _PREFIX = 'f2-';
return {
/**
* The APP class should be applied to the DOM Element that surrounds the
* entire app, including any extra html that surrounds the APP\_CONTAINER
* that is inserted by the container. See the
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object.
* @property APP
* @type string
* @static
* @final
*/
APP: _PREFIX + 'app',
/**
* The APP\_CONTAINER class should be applied to the outermost DOM Element
* of the app.
* @property APP_CONTAINER
* @type string
* @static
* @final
*/
APP_CONTAINER: _PREFIX + 'app-container',
/**
* The APP\_TITLE class should be applied to the DOM Element that contains
* the title for an app. If this class is not present, then
* F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function.
* @property APP_TITLE
* @type string
* @static
* @final
*/
APP_TITLE: _PREFIX + 'app-title',
/**
* The APP\_VIEW class should be applied to the DOM Element that contains
* a view for an app. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is.
* @property APP_VIEW
* @type string
* @static
* @final
*/
APP_VIEW: _PREFIX + 'app-view',
/**
* APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that
* trigger an
* {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE
* event. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger.
* @property APP_VIEW_TRIGGER
* @type string
* @static
* @final
*/
APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger',
/**
* The MASK class is applied to the overlay element that is created
* when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is
* fired.
* @property MASK
* @type string
* @static
* @final
*/
MASK: _PREFIX + 'mask',
/**
* The MASK_CONTAINER class is applied to the Element that is passed into
* the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method.
* @property MASK_CONTAINER
* @type string
* @static
* @final
*/
MASK_CONTAINER: _PREFIX + 'mask-container'
};
})(),
/**
* Events constants
* @class F2.Constants.Events
*/
Events: (function() {
/** @private */
var _APP_EVENT_PREFIX = 'App.';
/** @private */
var _CONTAINER_EVENT_PREFIX = 'Container.';
return {
/**
* The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an
* app. It is up to the app developer to fire this event.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property APP_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange',
/**
* The APP\_WIDTH\_CHANGE event will be fired by the container when the
* width of an app is changed. The app's instanceId should be concatenated
* to this constant.
* Returns an object with the gridSize and width in pixels:
*
* { gridSize:8, width:620 }
*
* @property APP_WIDTH_CHANGE
* @type string
* @static
* @final
*/
APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.',
/**
* The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed
* at the container level. This event should only be fired by the
* container or container provider.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property CONTAINER_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange',
/**
* The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when
* the width of the container has changed.
* @property CONTAINER_WIDTH_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange'
};
})(),
JSONP_CALLBACK: 'F2_jsonpCallback_',
/**
* Constants for use with cross-domain sockets
* @class F2.Constants.Sockets
* @protected
*/
Sockets: {
/**
* The EVENT message is sent whenever
* F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired
* @property EVENT
* @type string
* @static
* @final
*/
EVENT: '__event__',
/**
* The LOAD message is sent when an iframe socket initially loads.
* Returns a JSON string that represents:
*
* [ App, AppManifest]
*
* @property LOAD
* @type string
* @static
* @final
*/
LOAD: '__socketLoad__',
/**
* The RPC message is sent when a method is passed up from within a secure
* app page.
* @property RPC
* @type string
* @static
* @final
*/
RPC: '__rpc__',
/**
* The RPC\_CALLBACK message is sent when a call back from an RPC method is
* fired.
* @property RPC_CALLBACK
* @type string
* @static
* @final
*/
RPC_CALLBACK: '__rpcCallback__',
/**
* The UI\_RPC message is sent when a UI method called.
* @property UI_RPC
* @type string
* @static
* @final
*/
UI_RPC: '__uiRpc__'
},
/**
* The available view types to apps. The view should be specified by applying
* the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the
* containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the
* Element as well which defines what view type is represented.
* The `hide` class can be applied to views that should be hidden by default.
* @class F2.Constants.Views
*/
Views: {
/**
* The DATA_ATTRIBUTE should be placed on the DOM Element that contains the
* view.
* @property DATA_ATTRIBUTE
* @type string
* @static
* @final
*/
DATA_ATTRIBUTE: 'data-f2-view',
/**
* The ABOUT view gives details about the app.
* @property ABOUT
* @type string
* @static
* @final
*/
ABOUT: 'about',
/**
* The HELP view provides users with help information for using an app.
* @property HELP
* @type string
* @static
* @final
*/
HELP: 'help',
/**
* The HOME view is the main view for an app. This view should always
* be provided by an app.
* @property HOME
* @type string
* @static
* @final
*/
HOME: 'home',
/**
* The REMOVE view is a special view that handles the removal of an app
* from the container.
* @property REMOVE
* @type string
* @static
* @final
*/
REMOVE: 'remove',
/**
* The SETTINGS view provides users the ability to modify advanced settings
* for an app.
* @property SETTINGS
* @type string
* @static
* @final
*/
SETTINGS: 'settings'
}
});
/**
* Handles [Context](../../app-development.html#context) passing from
* containers to apps and apps to apps.
* @class F2.Events
*/
F2.extend('Events', (function() {
// init EventEmitter
var _events = new EventEmitter2({
wildcard:true
});
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
return {
/**
* Same as F2.Events.emit except that it will not send the event
* to all sockets.
* @method _socketEmit
* @private
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
_socketEmit: function() {
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Execute each of the listeners that may be listening for the specified
* event name in order with the list of arguments.
* @method emit
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
emit: function() {
F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments));
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Adds a listener that will execute n times for the event before being
* removed. The listener is invoked only the first time the event is
* fired, after which it is removed.
* @method many
* @param {string} event The event name
* @param {int} timesToListen The number of times to execute the event
* before being removed
* @param {function} listener The function to be fired when the event is
* emitted
*/
many: function(event, timesToListen, listener) {
return _events.many(event, timesToListen, listener);
},
/**
* Remove a listener for the specified event.
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
*/
off: function(event, listener) {
return _events.off(event, listener);
},
/**
* Adds a listener for the specified event
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
on: function(event, listener){
return _events.on(event, listener);
},
/**
* Adds a one time listener for the event. The listener is invoked only
* the first time the event is fired, after which it is removed.
* @method once
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
once: function(event, listener) {
return _events.once(event, listener);
}
};
})());
/**
* Handles socket communication between the container and secure apps
* @class F2.Rpc
*/
F2.extend('Rpc', (function(){
var _callbacks = {};
var _secureAppPagePath = '';
var _apps = {};
var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT);
var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC);
var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK);
var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD);
var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC);
/**
* Creates a socket connection from the app to the container using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createAppToContainerSocket
* @private
*/
var _createAppToContainerSocket = function() {
var appConfig; // socket closure
var isLoaded = false;
// its possible for messages to be received before the socket load event has
// happened. We'll save off these messages and replay them once the socket
// is ready
var messagePlayback = [];
var socket = new easyXDM.Socket({
onMessage: function(message, origin){
// handle Socket Load
if (!isLoaded && _rSocketLoad.test(message)) {
message = message.replace(_rSocketLoad, '');
var appParts = F2.parse(message);
// make sure we have the AppConfig and AppManifest
if (appParts.length == 2) {
appConfig = appParts[0];
// save socket
_apps[appConfig.instanceId] = {
config:appConfig,
socket:socket
};
// register app
F2.registerApps([appConfig], [appParts[1]]);
// socket message playback
jQuery.each(messagePlayback, function(i, e) {
_onMessage(appConfig, message, origin);
});
isLoaded = true;
}
} else if (isLoaded) {
// pass everyting else to _onMessage
_onMessage(appConfig, message, origin);
} else {
//F2.log('socket not ready, queuing message', message);
messagePlayback.push(message);
}
}
});
};
/**
* Creates a socket connection from the container to the app using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createContainerToAppSocket
* @private
* @param {appConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The F2.AppManifest object
*/
var _createContainerToAppSocket = function(appConfig, appManifest) {
var container = jQuery(appConfig.root);
if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) {
container.find('.' + F2.Constants.Css.APP_CONTAINER);
}
if (!container.length) {
F2.log('Unable to locate app in order to establish secure connection.');
return;
}
var iframeProps = {
scrolling:'no',
style:{
width:'100%'
}
};
if (appConfig.height) {
iframeProps.style.height = appConfig.height + 'px';
}
var socket = new easyXDM.Socket({
remote: _secureAppPagePath,
container: container.get(0),
props:iframeProps,
onMessage: function(message, origin) {
// pass everything to _onMessage
_onMessage(appConfig, message, origin);
},
onReady: function() {
socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer));
}
});
return socket;
};
/**
* @method _createRpcCallback
* @private
* @param {string} instanceId The app's Instance ID
* @param {function} callbackId The callback ID
* @return {function} A function to make the RPC call
*/
var _createRpcCallback = function(instanceId, callbackId) {
return function() {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC_CALLBACK,
callbackId,
[].slice.call(arguments).slice(2)
);
};
};
/**
* Handles messages that come across the sockets
* @method _onMessage
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} message The socket message
* @param {string} origin The originator
*/
var _onMessage = function(appConfig, message, origin) {
var obj, func;
function parseFunction(parent, functionName) {
var path = String(functionName).split('.');
for (var i = 0; i < path.length; i++) {
if (parent[path[i]] === undefined) {
parent = undefined;
break;
}
parent = parent[path[i]];
}
return parent;
}
function parseMessage(regEx, message, instanceId) {
var o = F2.parse(message.replace(regEx, ''));
// if obj.callbacks
// for each callback
// for each params
// if callback matches param
// replace param with _createRpcCallback(app.instanceId, callback)
if (o.params && o.params.length && o.callbacks && o.callbacks.length) {
jQuery.each(o.callbacks, function(i, c) {
jQuery.each(o.params, function(i, p) {
if (c == p) {
o.params[i] = _createRpcCallback(instanceId, c);
}
});
});
}
return o;
}
// handle UI Call
if (_rUiCall.test(message)) {
obj = parseMessage(_rUiCall, message, appConfig.instanceId);
func = parseFunction(appConfig.ui, obj.functionName);
// if we found the function, call it
if (func !== undefined) {
func.apply(appConfig.ui, obj.params);
} else {
F2.log('Unable to locate UI RPC function: ' + obj.functionName);
}
// handle RPC
} else if (_rRpc.test(message)) {
obj = parseMessage(_rRpc, message, appConfig.instanceId);
func = parseFunction(window, obj.functionName);
if (func !== undefined) {
func.apply(func, obj.params);
} else {
F2.log('Unable to locate RPC function: ' + obj.functionName);
}
// handle RPC Callback
} else if (_rRpcCallback.test(message)) {
obj = parseMessage(_rRpcCallback, message, appConfig.instanceId);
if (_callbacks[obj.functionName] !== undefined) {
_callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params);
delete _callbacks[obj.functionName];
}
// handle Events
} else if (_rEvents.test(message)) {
obj = parseMessage(_rEvents, message, appConfig.instanceId);
F2.Events._socketEmit.apply(F2.Events, obj);
}
};
/**
* Registers a callback function
* @method _registerCallback
* @private
* @param {function} callback The callback function
* @return {string} The callback ID
*/
var _registerCallback = function(callback) {
var callbackId = F2.guid();
_callbacks[callbackId] = callback;
return callbackId;
};
return {
/**
* Broadcast an RPC function to all sockets
* @method broadcast
* @param {string} messageType The message type
* @param {Array} params The parameters to broadcast
*/
broadcast: function(messageType, params) {
// check valid messageType
var message = messageType + F2.stringify(params);
jQuery.each(_apps, function(i, a) {
a.socket.postMessage(message);
});
},
/**
* Calls a remote function
* @method call
* @param {string} instanceId The app's Instance ID
* @param {string} messageType The message type
* @param {string} functionName The name of the remote function
* @param {Array} params An array of parameters to pass to the remote
* function. Any functions found within the params will be treated as a
* callback function.
*/
call: function(instanceId, messageType, functionName, params) {
// loop through params and find functions and convert them to callbacks
var callbacks = [];
jQuery.each(params, function(i, e) {
if (typeof e === 'function') {
var cid = _registerCallback(e);
params[i] = cid;
callbacks.push(cid);
}
});
// check valid messageType
_apps[instanceId].socket.postMessage(
messageType + F2.stringify({
functionName:functionName,
params:params,
callbacks:callbacks
})
);
},
/**
* Init function which tells F2.Rpc whether it is running at the container-
* level or the app-level. This method is generally called by
* F2.{{#crossLink "F2/init"}}{{/crossLink}}
* @method init
* @param {string} [secureAppPagePath] The
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath
* property
*/
init: function(secureAppPagePath) {
_secureAppPagePath = secureAppPagePath;
if (!_secureAppPagePath) {
_createAppToContainerSocket();
}
},
/**
* Determines whether the Instance ID is considered to be 'remote'. This is
* determined by checking if 1) the app has an open socket and 2) whether
* F2.Rpc is running inside of an iframe
* @method isRemote
* @param {string} instanceId The Instance ID
* @return {bool} True if there is an open socket
*/
isRemote: function(instanceId) {
return (
// we have an app
_apps[instanceId] !== undefined &&
// the app is secure
_apps[instanceId].config.isSecure &&
// we can't access the iframe
jQuery(_apps[instanceId].config.root).find('iframe').length === 0
);
},
/**
* Creates a container-to-app or app-to-container socket for communication
* @method register
* @param {F2.AppConfig} [appConfig] The F2.AppConfig object
* @param {F2.AppManifest} [appManifest] The F2.AppManifest object
*/
register: function(appConfig, appManifest) {
if (!!appConfig && !!appManifest) {
_apps[appConfig.instanceId] = {
config:appConfig,
socket:_createContainerToAppSocket(appConfig, appManifest)
};
} else {
F2.log('Unable to register socket connection. Please check container configuration.');
}
}
};
})());
F2.extend('UI', (function(){
var _containerConfig;
/**
* UI helper methods
* @class F2.UI
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object
*/
var UI_Class = function(appConfig) {
var _appConfig = appConfig;
var $root = jQuery(appConfig.root);
var _updateHeight = function(height) {
height = height || jQuery(_appConfig.root).outerHeight();
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'updateHeight',
[
height
]
);
} else {
_appConfig.height = height;
$root.find('iframe').height(_appConfig.height);
}
};
return {
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
*/
hideMask: function(selector) {
F2.UI.hideMask(_appConfig.instanceId, selector);
},
/**
* Helper methods for creating and using Modals
* @class F2.UI.Modals
* @for F2.UI
*/
Modals: (function(){
var _renderAlert = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Alert!</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button class="btn btn-primary btn-ok">OK</button>',
'</div>',
'</div>'
].join('');
};
var _renderConfirm = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Confirm</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button type="button" class="btn btn-primary btn-ok">OK</button>',
'<button type="button" class="btn btn-cancel">Cancel</button">',
'</div>',
'</div>'
].join('');
};
return {
/**
* Display an alert message on the page
* @method alert
* @param {string} message The message to be displayed
* @param {function} [callback] The callback to be fired when the user
* closes the dialog
* @for F2.UI.Modals
*/
alert: function(message, callback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.alert()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.alert',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderAlert(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-primary').on('click', function() {
jQuery(modal).modal('hide').remove();
(callback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
},
/**
* Display a confirm message on the page
* @method confirm
* @param {string} message The message to be displayed
* @param {function} okCallback The function that will be called when the OK
* button is pressed
* @param {function} cancelCallback The function that will be called when
* the Cancel button is pressed
* @for F2.UI.Modals
*/
confirm: function(message, okCallback, cancelCallback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.confirm()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.confirm',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderConfirm(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-ok').on('click', function() {
jQuery(modal).modal('hide').remove();
(okCallback || jQuery.noop)();
});
jQuery(modal).find('.btn-cancel').on('click', function() {
jQuery(modal).modal('hide').remove();
(cancelCallback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
}
};
})(),
/**
* Sets the title of the app as shown in the browser. Depending on the
* container HTML, this method may do nothing if the container has not been
* configured properly or else the container provider does not allow Title's
* to be set.
* @method setTitle
* @params {string} title The title of the app
* @for F2.UI
*/
setTitle: function(title) {
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'setTitle',
[
title
]
);
} else {
jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title);
}
},
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
showMask: function(selector, showLoader) {
F2.UI.showMask(_appConfig.instanceId, selector, showLoader);
},
/**
* For secure apps, this method updates the size of the iframe that
* contains the app. **Note: It is recommended that app developers call
* this method anytime Elements are added or removed from the DOM**
* @method updateHeight
* @params {int} height The height of the app
*/
updateHeight: _updateHeight,
/**
* Helper methods for creating and using Views
* @class F2.UI.Views
* @for F2.UI
*/
Views: (function(){
var _events = new EventEmitter2();
var _rValidEvents = /change/i;
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
var _isValid = function(eventName) {
if (_rValidEvents.test(eventName)) {
return true;
} else {
F2.log('"' + eventName + '" is not a valid F2.UI.Views event name');
return false;
}
};
return {
/**
* Change the current view for the app or add an event listener
* @method change
* @param {string|function} [input] If a string is passed in, the view
* will be changed for the app. If a function is passed in, a change
* event listener will be added.
* @for F2.UI.Views
*/
change: function(input) {
if (typeof input === 'function') {
this.on('change', input);
} else if (typeof input === 'string') {
if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Views.change',
[].slice.call(arguments)
);
} else if (F2.inArray(input, _appConfig.views)) {
jQuery('.' + F2.Constants.Css.APP_VIEW, $root)
.addClass('hide')
.filter('[data-f2-view="' + input + '"]', $root)
.removeClass('hide');
_updateHeight();
_events.emit('change', input);
}
}
},
/**
* Removes a view event listener
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
* @for F2.UI.Views
*/
off: function(event, listener) {
if (_isValid(event)) {
_events.off(event, listener);
}
},
/**
* Adds a view event listener
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
* @for F2.UI.Views
*/
on: function(event, listener) {
if (_isValid(event)) {
_events.on(event, listener);
}
}
};
})()
};
};
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
* @for F2.UI
*/
UI_Class.hideMask = function(instanceId, selector) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.hideMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.hideMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector
]
);
} else {
var container = jQuery(selector);
container.find('> .' + F2.Constants.Css.MASK).remove();
container.removeClass(F2.Constants.Css.MASK_CONTAINER);
// if the element contains this data property, we need to reset static
// position
if (container.data(F2.Constants.Css.MASK_CONTAINER)) {
container.css({'position':'static'});
}
}
};
/**
*
* @method init
* @static
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
UI_Class.init = function(containerConfig) {
_containerConfig = containerConfig;
// set defaults
_containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {});
};
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
UI_Class.showMask = function(instanceId, selector, showLoading) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.showMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.showMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector,
showLoading
]
);
} else {
if (showLoading && !_containerConfig.UI.Mask.loadingIcon) {
F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();');
}
var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER);
var mask = jQuery('<div>')
.height('100%' /*container.outerHeight()*/)
.width('100%' /*container.outerWidth()*/)
.addClass(F2.Constants.Css.MASK);
// set inline styles if useClasses is false
if (!_containerConfig.UI.Mask.useClasses) {
mask.css({
'background-color':_containerConfig.UI.Mask.backgroundColor,
'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '',
'background-position':'50% 50%',
'background-repeat':'no-repeat',
'display':'block',
'left':0,
'min-height':30,
'padding':0,
'position':'absolute',
'top':0,
'z-index':_containerConfig.UI.Mask.zIndex,
'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')',
'opacity':_containerConfig.UI.Mask.opacity
});
}
// only set the position if the container is currently static
if (container.css('position') === 'static') {
container.css({'position':'relative'});
// setting this data property tells hideMask to set the position
// back to static
container.data(F2.Constants.Css.MASK_CONTAINER, true);
}
// add the mask to the container
container.append(mask);
}
};
return UI_Class;
})());
/**
* Root namespace of the F2 SDK
* @module f2
* @class F2
*/
F2.extend('', (function(){
var _apps = {};
var _config = false;
var _bUsesAppHandlers = false;
var _sAppHandlerToken = F2.AppHandlers.__f2GetToken();
/**
* Appends the app's html to the DOM
* @method _afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
* @return {Element} The DOM Element that contains the app
*/
var _afterAppRender = function(appConfig, html) {
var handler = _config.afterAppRender || function(appConfig, html) {
return jQuery(html).appendTo('body');
};
var appContainer = handler(appConfig, html);
if (!!_config.afterAppRender && !appContainer) {
F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app');
return;
} else {
// apply APP class and Instance ID
jQuery(appContainer).addClass(F2.Constants.Css.APP);
return appContainer.get(0);
}
};
/**
* Renders the html for an app.
* @method _appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
*/
var _appRender = function(appConfig, html) {
// apply APP_CONTAINER class
html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId));
// optionally apply wrapper html
if (_config.appRender) {
html = _config.appRender(appConfig, html);
}
// apply APP class and instanceId
return _outerHtml(html);
};
/**
* Rendering hook to allow containers to render some html prior to an app
* loading
* @method _beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
var _beforeAppRender = function(appConfig) {
var handler = _config.beforeAppRender || jQuery.noop;
return handler(appConfig);
};
/**
* Adds properties to the AppConfig object
* @method _createAppConfig
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with
* necessary properties
*/
var _createAppConfig = function(appConfig) {
// make a copy of the app config to ensure that the original is not modified
appConfig = jQuery.extend(true, {}, appConfig);
// create the instanceId for the app
appConfig.instanceId = appConfig.instanceId || F2.guid();
// default the views if not provided
appConfig.views = appConfig.views || [];
if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) {
appConfig.views.push(F2.Constants.Views.HOME);
}
return appConfig;
};
/**
* Adds properties to the ContainerConfig object to take advantage of defaults
* @method _hydrateContainerConfig
* @private
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
var _hydrateContainerConfig = function(containerConfig) {
if (!containerConfig.scriptErrorTimeout){
containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout;
}
if (containerConfig.debugMode !== true){
containerConfig.debugMode = F2.ContainerConfig.debugMode;
}
};
/**
* Attach app events
* @method _initAppEvents
* @private
*/
var _initAppEvents = function (appConfig) {
jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) {
event.preventDefault();
var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase();
// handle the special REMOVE view
if (view == F2.Constants.Views.REMOVE) {
F2.removeApp(appConfig.instanceId);
} else {
appConfig.ui.Views.change(view);
}
});
};
/**
* Attach container Events
* @method _initContainerEvents
* @private
*/
var _initContainerEvents = function() {
var resizeTimeout;
var resizeHandler = function() {
F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE);
};
jQuery(window).on('resize', function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeHandler, 100);
});
};
/**
* Has the container been init?
* @method _isInit
* @private
* @return {bool} True if the container has been init
*/
var _isInit = function() {
return !!_config;
};
/**
* Instantiates each app from it's appConfig and stores that in a local private collection
* @method _createAppInstance
* @private
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
*/
var _createAppInstance = function(appConfig, appContent){
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// instantiate F2.App
if (F2.Apps[appConfig.appId] !== undefined) {
if (typeof F2.Apps[appConfig.appId] === 'function') {
// IE
setTimeout(function() {
_apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root);
if (_apps[appConfig.instanceId].app['init'] !== undefined) {
_apps[appConfig.instanceId].app.init();
}
}, 0);
} else {
F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')');
}
}
};
/**
* Loads the app's html/css/javascript
* @method loadApp
* @private
* @param {Array} appConfigs An array of
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
* @param {F2.AppManifest} [appManifest] The AppManifest object
*/
var _loadApps = function(appConfigs, appManifest) {
appConfigs = [].concat(appConfigs);
// check for secure app
if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) {
_loadSecureApp(appConfigs[0], appManifest);
return;
}
// check that the number of apps in manifest matches the number requested
if (appConfigs.length != appManifest.apps.length) {
F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest);
return;
}
var scripts = appManifest.scripts || [];
var styles = appManifest.styles || [];
var inlines = appManifest.inlineScripts || [];
var scriptCount = scripts.length;
var scriptsLoaded = 0;
var appInit = function() {
jQuery.each(appConfigs, function(i, a) {
_createAppInstance(a, appManifest.apps[i]);
});
};
//Check to see if any of the ways a file can be ready are available as properties on the file's element (borrowed from yepnope)
var isFileReady = function(readyState) {
return ( !readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized' );
};
var _onload = function(e){
if ( e.type == 'load' || isFileReady((e.currentTarget || e.srcElement).readyState) ){
//done, cleanup
var script = e.currentTarget || e.srcElement;
if (script.detachEvent){
script.detachEvent('onreadystatechange', _onload);//IE
} else {
removeEventListener(script, _onload, 'load');
removeEventListener(script, _error, 'error');
}
}
//are we done loading all scripts for this app?
if (++scriptsLoaded == scriptCount) {
evalInlines();
appInit();
}
};
var _error = function(e){
//log and emit event for the failed (400,500) scripts
setTimeout(function(){
var evtData = {
src: e.target.src,
appId: appConfigs[0].appId
};
//send error to console
F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\'');
//emit event
F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData);
}, _config.scriptErrorTimeout);//defaults to 7000
};
//eval inlines
var evalInlines = function(){
jQuery.each(inlines, function(i, e) {
try {
eval(e);
} catch (exception) {
F2.log('Error loading inline script: ' + exception + '\n\n' + e);
}
});
};
// load styles, see #101
var stylesFragment = null,
useCreateStyleSheet = !!document.createStyleSheet;
jQuery.each(styles, function(i, e) {
if (useCreateStyleSheet) {
document.createStyleSheet(e);
} else {
stylesFragment = stylesFragment || [];
stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>');
}
});
if (stylesFragment){
jQuery('head').append(stylesFragment.join(''));
}
// load html
jQuery.each(appManifest.apps, function(i, a) {
if(!_bUsesAppHandlers) {
// load html and save the root node
appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html));
} else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfigs[i], // the app config
_outerHtml(a.html)
);
var appId = appConfigs[i].appId;
if (!appConfigs[i].root) {
throw('Root for ' +appId+ ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.');
}
var $root = jQuery(appConfigs[i].root);
if ($root.parents('body:first').length === 0) {
throw('App root for ' +appId+ ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfigs[i] // the app config
);
if(!F2.isNativeDOMNode(appConfigs[i].root)) {
throw('App root for ' +appId+ ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.');
}
$root.addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId);
}
// init events
_initAppEvents(appConfigs[i]);
});
// load scripts and eval inlines once complete
jQuery.each(scripts, function(i, e) {
var doc = document,
script = doc.createElement('script'),
resourceUrl = e;
//if in debugMode, add cache buster to each script URL
if (_config.debugMode){
resourceUrl += '?cachebuster=' + new Date().getTime();
}
//scripts needed to be loaded in order they're defined in the AppManifest
script.async = false;
//add other attrs
script.src = resourceUrl;
script.type = 'text/javascript';
script.charset = 'utf-8';
//attach load event to script to evaluate inline scripts and init the AppClass
if (script.attachEvent && !(script.attachEvent.toString && script.attachEvent.toString().indexOf('[native code') < 0)){//for IE, from requirejs
script.attachEvent('onreadystatechange', _onload);
} else {
script.addEventListener('load', _onload, false);
//attach error event for 400s and 500s
script.addEventListener('error', _error, false);
}
doc.body.appendChild(script);
});
// if no scripts were to be processed, fire the appInit event
if (!scriptCount) {
evalInlines();
appInit();
}
};
/**
* Loads the app's html/css/javascript into an iframe
* @method loadSecureApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the
* page.
*/
var _loadSecureApp = function(appConfig, appManifest) {
// make sure the container is configured for secure apps
if (_config.secureAppPagePath) {
if(!_bUsesAppHandlers) {
// create the html container for the iframe
appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>'));
} else {
var $root = jQuery(appConfig.root);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfig, // the app config
appManifest.html
);
if ($root.parents('body:first').length === 0) {
throw('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfig // the app config
);
if (!appConfig.root) {
throw('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
if (!F2.isNativeDOMNode(appConfig.root)) {
throw('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId);
}
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// init events
_initAppEvents(appConfig);
// create RPC socket
F2.Rpc.register(appConfig, appManifest);
} else {
F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.');
}
};
var _outerHtml = function(html) {
return jQuery('<div></div>').append(html).html();
};
/**
* Checks if the app is valid
* @method _validateApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @returns {bool} True if the app is valid
*/
var _validateApp = function(appConfig) {
// check for valid app configurations
if (!appConfig.appId) {
F2.log('"appId" missing from app object');
return false;
} else if (!appConfig.root && !appConfig.manifestUrl) {
F2.log('"manifestUrl" missing from app object');
return false;
}
return true;
};
/**
* Checks if the ContainerConfig is valid
* @method _validateContainerConfig
* @private
* @returns {bool} True if the config is valid
*/
var _validateContainerConfig = function() {
if (_config) {
if (_config.xhr) {
if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) {
throw('ContainerConfig.xhr should be a function or an object');
}
if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') {
throw('ContainerConfig.xhr.dataType should be a function');
}
if (_config.xhr.type && typeof _config.xhr.type !== 'function') {
throw('ContainerConfig.xhr.type should be a function');
}
if (_config.xhr.url && typeof _config.xhr.url !== 'function') {
throw('ContainerConfig.xhr.url should be a function');
}
}
}
return true;
};
return {
/**
* Gets the current list of apps in the container
* @method getContainerState
* @returns {Array} An array of objects containing the appId
*/
getContainerState: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.getContainerState()');
return;
}
return jQuery.map(_apps, function(app) {
return { appId: app.config.appId };
});
},
/**
* Initializes the container. This method must be called before performing
* any other actions in the container.
* @method init
* @param {F2.ContainerConfig} config The configuration object
*/
init: function(config) {
_config = config || {};
_validateContainerConfig();
_hydrateContainerConfig(_config);
// dictates whether we use the old logic or the new logic.
// TODO: Remove in v2.0
_bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender);
// only establish RPC connection if the container supports the secure app page
if (!!_config.secureAppPagePath || _config.isSecureAppPage) {
F2.Rpc.init(!!_config.secureAppPagePath ? _config.secureAppPagePath : false);
}
F2.UI.init(_config);
if (!_config.isSecureAppPage) {
_initContainerEvents();
}
},
/**
* Has the container been init?
* @method isInit
* @return {bool} True if the container has been init
*/
isInit: _isInit,
/**
* Begins the loading process for all apps and/or initialization process for pre-loaded apps.
* The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will
* contain the app's unique instanceId within the container. If the
* {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered
* to be a pre-loaded app and will be handled accordingly. Optionally, the
* {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those
* assets will be used instead of making a request.
* @method registerApps
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {Array} [appManifests] An array of
* {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* objects. This array must be the same length as the apps array that is
* objects. This array must be the same length as the apps array that is
* passed in. This can be useful if apps are loaded on the server-side and
* passed down to the client.
* @example
* Traditional App requests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app2',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Pre-loaded and tradition apps mixed.
*
* // Pre-loaded apps and traditional f2 app configs
* // you can preload the same app multiple times as long as you have a unique root for each
* var arConfigs = [
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-1',
* manifestUrl: ''
* },
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-2',
* manifestUrl: ''
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Apps with predefined manifests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app2', context: {}}
* ];
*
* // Pre requested manifest responses
* var arManifests = [
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App 2!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/App2Class.js'],
* styles: ['http://www.domain.com/css/App2Styles.css']
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs, arManifests);
*/
registerApps: function(appConfigs, appManifests) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.registerApps()');
return;
} else if (!appConfigs) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
}
var appStack = [];
var batches = {};
var callbackStack = {};
var haveManifests = false;
appConfigs = [].concat(appConfigs);
appManifests = [].concat(appManifests || []);
haveManifests = !!appManifests.length;
// appConfigs must have a length
if (!appConfigs.length) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
// ensure that the array of apps and manifests are qual
} else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) {
F2.log('The length of "apps" does not equal the length of "appManifests"');
return;
}
// validate each app and assign it an instanceId
// then determine which apps can be batched together
jQuery.each(appConfigs, function(i, a) {
// add properties and methods
a = _createAppConfig(a);
// Will set to itself, for preloaded apps, or set to null for apps that aren't already
// on the page.
a.root = a.root || null;
// we validate the app after setting the root property because pre-load apps do no require
// manifest url
if (!_validateApp(a)) {
return; // move to the next app
}
// save app
_apps[a.instanceId] = { config:a };
// If the root property is defined then this app is considered to be preloaded and we will
// run it through that logic.
if(a.root)
{
if((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root))
{
F2.log('AppConfig invalid for pre-load, not a valid string and not dom node');
F2.log('AppConfig instance:', a);
throw('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.');
}
else if(jQuery(a.root).length != 1)
{
F2.log('AppConfig invalid for pre-load, root not unique');
F2.log('AppConfig instance:', a);
F2.log('Number of dom node instances:', jQuery(a.root).length);
throw('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.');
}
// instantiate F2.App
_createAppInstance(a);
// init events
_initAppEvents(a);
// Continue on in the .each loop, no need to continue because the app is on the page
// the js in initialized, and it is ready to role.
return; // equivalent to continue in .each
}
if(!_bUsesAppHandlers)
{
// fire beforeAppRender
a.root = _beforeAppRender(a);
}
else
{
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_CREATE_ROOT,
a // the app config
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_BEFORE,
a // the app config
);
}
// if we have the manifest, go ahead and load the app
if (haveManifests) {
_loadApps(a, appManifests[i]);
} else {
// check if this app can be batched
if (a.enableBatchRequests && !a.isSecure) {
batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || [];
batches[a.manifestUrl.toLowerCase()].push(a);
} else {
appStack.push({
apps:[a],
url:a.manifestUrl
});
}
}
});
// we don't have the manifests, go ahead and load them
if (!haveManifests) {
// add the batches to the appStack
jQuery.each(batches, function(i, b) {
appStack.push({ url:i, apps:b });
});
// if an app is being loaded more than once on the page, there is the
// potential that the jsonp callback will be clobbered if the request
// for the AppManifest for the app comes back at the same time as
// another request for the same app. We'll create a callbackStack
// that will ensure that requests for the same app are loaded in order
// rather than at the same time
jQuery.each(appStack, function(i, req) {
// define the callback function based on the first app's App ID
var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId;
// push the request onto the callback stack
callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || [];
callbackStack[jsonpCallback].push(req);
});
// loop through each item in the callback stack and make the request
// for the AppManifest. When the request is complete, pop the next
// request off the stack and make the request.
jQuery.each(callbackStack, function(i, requests) {
var manifestRequest = function(jsonpCallback, req) {
if (!req) { return; }
// setup defaults and callbacks
var url = req.url,
type = 'GET',
dataType = 'jsonp',
completeFunc = function() {
manifestRequest(i, requests.pop());
},
errorFunc = function() {
jQuery.each(req.apps, function(idx,item){
F2.log('Removed failed ' +item.name+ ' app', item);
F2.removeApp(item.instanceId);
});
},
successFunc = function(appManifest) {
_loadApps(req.apps, appManifest);
};
// optionally fire xhr overrides
if (_config.xhr && _config.xhr.dataType) {
dataType = _config.xhr.dataType(req.url, req.apps);
if (typeof dataType !== 'string') {
throw('ContainerConfig.xhr.dataType should return a string');
}
}
if (_config.xhr && _config.xhr.type) {
type = _config.xhr.type(req.url, req.apps);
if (typeof type !== 'string') {
throw('ContainerConfig.xhr.type should return a string');
}
}
if (_config.xhr && _config.xhr.url) {
url = _config.xhr.url(req.url, req.apps);
if (typeof url !== 'string') {
throw('ContainerConfig.xhr.url should return a string');
}
}
// setup the default request function if an override is not present
var requestFunc = _config.xhr;
if (typeof requestFunc !== 'function') {
requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) {
jQuery.ajax({
url: url,
type: type,
data: {
params: F2.stringify(req.apps, F2.appConfigReplacer)
},
jsonp: false, // do not put 'callback=' in the query string
jsonpCallback: jsonpCallback, // Unique function name
dataType: dataType,
success: successCallback,
error: function(jqxhr, settings, exception) {
F2.log('Failed to load app(s)', exception.toString(), req.apps);
errorCallback();
},
complete: completeCallback
});
};
}
requestFunc(url, req.apps, successFunc, errorFunc, completeFunc);
};
manifestRequest(i, requests.pop());
});
}
},
/**
* Removes all apps from the container
* @method removeAllApps
*/
removeAllApps: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeAllApps()');
return;
}
jQuery.each(_apps, function(i, a) {
F2.removeApp(a.config.instanceId);
});
},
/**
* Removes an app from the container
* @method removeApp
* @param {string} instanceId The app's instanceId
*/
removeApp: function(instanceId) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeApp()');
return;
}
if (_apps[instanceId]) {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_AFTER,
_apps[instanceId] // the app instance
);
delete _apps[instanceId];
}
}
};
})());
exports.F2 = F2;
if (typeof define !== 'undefined' && define.amd) {
define(function() {
return F2;
});
}
})(typeof exports !== 'undefined' ? exports : window); |
src/router-html.js | philcockfield/react-server-pages | /* eslint global-require:0 */
import R from 'ramda';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import fs from 'fs-extra';
import fsPath from 'path';
import Url from 'url';
import * as util from 'js-util';
const NODE_ENV = process.env.NODE_ENV || 'development';
const asValues = (obj, args) => {
const result = R.clone(obj);
Object.keys(obj).forEach(key => {
const value = obj[key];
if (R.is(Function, value)) {
result[key] = value(args); // Convert the function into a value.
} else if (R.is(Object, value)) {
result[key] = asValues(value, args); // <== RECURSION.
}
});
return result;
};
const getFilePath = (basePath, name, extension) => {
let path;
name = name.charAt(0).toUpperCase() + name.slice(1); // Capitalize the file/folder name.
// Look first for the existence of a stand-alone file.
path = fsPath.join(basePath, `${ name }.${ extension }`);
if (fs.existsSync(path)) { return path; }
// Look for the file within a folder.
path = fsPath.join(basePath, name, `${ name }.${ extension }`);
if (fs.existsSync(path)) { return path; }
return undefined;
};
export default (middleware, paths, routes, data) => {
const getLayout = (route) => {
const layoutName = route.layout || 'Html';
const path = getFilePath(paths.layouts, layoutName, 'jsx');
if (!path) { throw new Error(`A layout named '${ layoutName }' does not exist.`); }
return require(path).default;
};
const getPage = (route) => {
const pageName = route.page;
const path = getFilePath(paths.pages, pageName, 'jsx');
if (!path) { throw new Error(`A page named '${ pageName }' does not exist.`); }
return require(path).default;
};
function getData(route, url) {
return R.is(Function, data) ? data({ route, url }) : data;
}
const render = (req, res, route) => {
// Setup initial conditions.
const host = req.get('host');
const params = Object
.keys(req.params)
.forEach(key => { req.params[key] = util.toType(req.params[key]); });
const url = {
params,
path: req.url,
pathname: Url.parse(req.url).pathname,
query: req.query,
pattern: route.pattern,
protocol: req.secure ? 'https:' : 'http',
host: host.split(':')[0],
port: host.split(':')[1],
};
const args = { url };
route = asValues(route, args);
// Prepare the page body.
const requestData = { url };
const layoutData = getData(route, url);
const pageProps = route.props || {};
const pageData = pageProps.data || layoutData;
if (pageData) {
pageProps.data = pageData;
}
pageProps.request = requestData;
const pageBody = React.createElement(getPage(route), pageProps);
// Prepare the root <Html> page props.
const layoutProps = {
title: route.title,
body: pageBody,
data: layoutData,
env: NODE_ENV,
page: { name: route.page },
request: requestData,
};
// Convert the page-layout into HTML.
const layout = React.createElement(getLayout(route), layoutProps);
const html = ReactDOMServer.renderToStaticMarkup(layout);
res.send(html);
};
// Register each route as a GET handler.
Object.keys(routes).forEach(pattern => {
const route = routes[pattern];
route.pattern = pattern;
middleware.get(pattern, (req, res) => { render(req, res, route); });
});
};
|
ajax/libs/yui/3.10.3/event-focus/event-focus-min.js | dylannnn/cdnjs | YUI.add("event-focus",function(e,t){function u(t,r,u){var a="_"+t+"Notifiers";e.Event.define(t,{_useActivate:o,_attach:function(i,s,o){return e.DOM.isWindow(i)?n._attach([t,function(e){s.fire(e)},i]):n._attach([r,this._proxy,i,this,s,o],{capture:!0})},_proxy:function(t,r,i){var s=t.target,f=t.currentTarget,l=s.getData(a),c=e.stamp(f._node),h=o||s!==f,p;r.currentTarget=i?s:f,r.container=i?f:null,l?h=!0:(l={},s.setData(a,l),h&&(p=n._attach([u,this._notify,s._node]).sub,p.once=!0)),l[c]||(l[c]=[]),l[c].push(r),h||this._notify(t)},_notify:function(t,n){var r=t.currentTarget,i=r.getData(a),o=r.ancestors(),u=r.get("ownerDocument"),f=[],l=i?e.Object.keys(i).length:0,c,h,p,d,v,m,g,y,b,w;r.clearData(a),o.push(r),u&&o.unshift(u),o._nodes.reverse(),l&&(m=l,o.some(function(t){var n=e.stamp(t),r=i[n],s,o;if(r){l--;for(s=0,o=r.length;s<o;++s)r[s].handle.sub.filter&&f.push(r[s])}return!l}),l=m);while(l&&(c=o.shift())){d=e.stamp(c),h=i[d];if(h){for(g=0,y=h.length;g<y;++g){p=h[g],b=p.handle.sub,v=!0,t.currentTarget=c,b.filter&&(v=b.filter.apply(c,[c,t].concat(b.args||[])),f.splice(s(f,p),1)),v&&(t.container=p.container,w=p.fire(t));if(w===!1||t.stopped===2)break}delete h[d],l--}if(t.stopped!==2)for(g=0,y=f.length;g<y;++g){p=f[g],b=p.handle.sub,b.filter.apply(c,[c,t].concat(b.args||[]))&&(t.container=p.container,t.currentTarget=c,w=p.fire(t));if(w===!1||t.stopped===2)break}if(t.stopped)break}},on:function(e,t,n){t.handle=this._attach(e._node,n)},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,s){i(s)&&(n.filter=function(n){return e.Selector.test(n._node,s,t===n?null:t._node)}),n.handle=this._attach(t._node,r,!0)},detachDelegate:function(e,t){t.handle.detach()}},!0)}var n=e.Event,r=e.Lang,i=r.isString,s=e.Array.indexOf,o=function(){var t=!1,n=e.config.doc,r;return n&&(r=n.createElement("p"),r.setAttribute("onbeforeactivate",";"),t=r.onbeforeactivate!==undefined),t}();o?(u("focus","beforeactivate","focusin"),u("blur","beforedeactivate","focusout")):(u("focus","focus","focus"),u("blur","blur","blur"))},"@VERSION@",{requires:["event-synthetic"]});
|
ajax/libs/mini-meteor/1.0.1/mini-meteor.min.js | iwdmb/cdnjs | (function(){var a=this,b=a._,d=Array.prototype,f=Object.prototype,l=d.push,k=d.slice,n=d.concat,p=f.toString,C=f.hasOwnProperty,f=Array.isArray,D=Object.keys,w=Function.prototype.bind,c=function(e){return e instanceof c?e:this instanceof c?void(this._wrapped=e):new c(e)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=c),exports._=c):a._=c;c.VERSION="1.7.0";var t=function(e,a,c){if(void 0===a)return e;switch(null==c?3:c){case 1:return function(c){return e.call(a,
c)};case 2:return function(c,g){return e.call(a,c,g)};case 3:return function(c,g,b){return e.call(a,c,g,b)};case 4:return function(c,g,b,d){return e.call(a,c,g,b,d)}}return function(){return e.apply(a,arguments)}};c.iteratee=function(e,a,g){return null==e?c.identity:c.isFunction(e)?t(e,a,g):c.isObject(e)?c.matches(e):c.property(e)};c.each=c.forEach=function(e,a,g){if(null==e)return e;a=t(a,g);var q=e.length;if(q===+q)for(g=0;q>g;g++)a(e[g],g,e);else{var b=c.keys(e);g=0;for(q=b.length;q>g;g++)a(e[b[g]],
b[g],e)}return e};c.map=c.collect=function(e,a,g){if(null==e)return[];a=c.iteratee(a,g);for(var q=e.length!==+e.length&&c.keys(e),b=(q||e).length,d=Array(b),m=0;b>m;m++)g=q?q[m]:m,d[m]=a(e[g],g,e);return d};c.reduce=c.foldl=c.inject=function(e,a,g,q){null==e&&(e=[]);a=t(a,q,4);var b,d=e.length!==+e.length&&c.keys(e),m=(d||e).length,f=0;if(3>arguments.length){if(!m)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[f++]:f++]}for(;m>f;f++)b=d?d[f]:f,g=a(g,e[b],b,e);return g};
c.reduceRight=c.foldr=function(e,a,g,b){null==e&&(e=[]);a=t(a,b,4);var h,d=e.length!==+e.length&&c.keys(e),f=(d||e).length;if(3>arguments.length){if(!f)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[--f]:--f]}for(;f--;)h=d?d[f]:f,g=a(g,e[h],h,e);return g};c.find=c.detect=function(e,a,g){var b;return a=c.iteratee(a,g),c.some(e,function(e,c,g){return a(e,c,g)?(b=e,!0):void 0}),b};c.filter=c.select=function(e,a,g){var b=[];return null==e?b:(a=c.iteratee(a,g),c.each(e,function(e,
c,g){a(e,c,g)&&b.push(e)}),b)};c.reject=function(e,a,g){return c.filter(e,c.negate(c.iteratee(a)),g)};c.every=c.all=function(e,a,g){if(null==e)return!0;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,!a(e[b],b,e))return!1;return!0};c.some=c.any=function(e,a,g){if(null==e)return!1;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,a(e[b],b,e))return!0;return!1};c.contains=c.include=function(e,
a){return null==e?!1:(e.length!==+e.length&&(e=c.values(e)),0<=c.indexOf(e,a))};c.invoke=function(e,a){var g=k.call(arguments,2),b=c.isFunction(a);return c.map(e,function(e){return(b?a:e[a]).apply(e,g)})};c.pluck=function(e,a){return c.map(e,c.property(a))};c.where=function(e,a){return c.filter(e,c.matches(a))};c.findWhere=function(e,a){return c.find(e,c.matches(a))};c.max=function(e,a,g){var b,h=-1/0,d=-1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g=
e[f],g>h&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(b>d||b===-1/0&&h===-1/0)&&(h=e,d=b)});return h};c.min=function(e,a,g){var b,h=1/0,d=1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g=e[f],h>g&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(d>b||1/0===b&&1/0===h)&&(h=e,d=b)});return h};c.shuffle=function(e){for(var a=e&&e.length===+e.length?e:c.values(e),g=a.length,b=Array(g),h=0;g>h;h++)e=c.random(0,h),e!==
h&&(b[h]=b[e]),b[e]=a[h];return b};c.sample=function(e,a,g){return null==a||g?(e.length!==+e.length&&(e=c.values(e)),e[c.random(e.length-1)]):c.shuffle(e).slice(0,Math.max(0,a))};c.sortBy=function(e,a,g){return a=c.iteratee(a,g),c.pluck(c.map(e,function(e,c,g){return{value:e,index:c,criteria:a(e,c,g)}}).sort(function(e,a){var c=e.criteria,g=a.criteria;if(c!==g){if(c>g||void 0===c)return 1;if(g>c||void 0===g)return-1}return e.index-a.index}),"value")};var u=function(e){return function(a,g,b){var d=
{};return g=c.iteratee(g,b),c.each(a,function(c,b){var q=g(c,b,a);e(d,c,q)}),d}};c.groupBy=u(function(e,a,g){c.has(e,g)?e[g].push(a):e[g]=[a]});c.indexBy=u(function(e,a,c){e[c]=a});c.countBy=u(function(e,a,g){c.has(e,g)?e[g]++:e[g]=1});c.sortedIndex=function(e,a,g,b){g=c.iteratee(g,b,1);a=g(a);b=0;for(var d=e.length;d>b;){var f=b+d>>>1;g(e[f])<a?b=f+1:d=f}return b};c.toArray=function(e){return e?c.isArray(e)?k.call(e):e.length===+e.length?c.map(e,c.identity):c.values(e):[]};c.size=function(e){return null==
e?0:e.length===+e.length?e.length:c.keys(e).length};c.partition=function(e,a,g){a=c.iteratee(a,g);var b=[],d=[];return c.each(e,function(e,c,g){(a(e,c,g)?b:d).push(e)}),[b,d]};c.first=c.head=c.take=function(e,a,c){return null==e?void 0:null==a||c?e[0]:0>a?[]:k.call(e,0,a)};c.initial=function(e,a,c){return k.call(e,0,Math.max(0,e.length-(null==a||c?1:a)))};c.last=function(e,a,c){return null==e?void 0:null==a||c?e[e.length-1]:k.call(e,Math.max(e.length-a,0))};c.rest=c.tail=c.drop=function(e,a,c){return k.call(e,
null==a||c?1:a)};c.compact=function(e){return c.filter(e,c.identity)};var v=function(e,a,g,b){if(a&&c.every(e,c.isArray))return n.apply(b,e);for(var d=0,f=e.length;f>d;d++){var m=e[d];c.isArray(m)||c.isArguments(m)?a?l.apply(b,m):v(m,a,g,b):g||b.push(m)}return b};c.flatten=function(e,a){return v(e,a,!1,[])};c.without=function(e){return c.difference(e,k.call(arguments,1))};c.uniq=c.unique=function(e,a,b,d){if(null==e)return[];c.isBoolean(a)||(d=b,b=a,a=!1);null!=b&&(b=c.iteratee(b,d));d=[];for(var h=
[],f=0,m=e.length;m>f;f++){var r=e[f];if(a)f&&h===r||d.push(r),h=r;else if(b){var k=b(r,f,e);0>c.indexOf(h,k)&&(h.push(k),d.push(r))}else 0>c.indexOf(d,r)&&d.push(r)}return d};c.union=function(){return c.uniq(v(arguments,!0,!0,[]))};c.intersection=function(e){if(null==e)return[];for(var a=[],b=arguments.length,d=0,h=e.length;h>d;d++){var f=e[d];if(!c.contains(a,f)){for(var m=1;b>m&&c.contains(arguments[m],f);m++);m===b&&a.push(f)}}return a};c.difference=function(e){var a=v(k.call(arguments,1),!0,
!0,[]);return c.filter(e,function(e){return!c.contains(a,e)})};c.zip=function(e){if(null==e)return[];for(var a=c.max(arguments,"length").length,b=Array(a),d=0;a>d;d++)b[d]=c.pluck(arguments,d);return b};c.object=function(a,c){if(null==a)return{};for(var b={},d=0,h=a.length;h>d;d++)c?b[a[d]]=c[d]:b[a[d][0]]=a[d][1];return b};c.indexOf=function(a,b,g){if(null==a)return-1;var d=0,h=a.length;if(g){if("number"!=typeof g)return d=c.sortedIndex(a,b),a[d]===b?d:-1;d=0>g?Math.max(0,h+g):g}for(;h>d;d++)if(a[d]===
b)return d;return-1};c.lastIndexOf=function(a,c,b){if(null==a)return-1;var d=a.length;for("number"==typeof b&&(d=0>b?d+b+1:Math.min(d,b+1));0<=--d;)if(a[d]===c)return d;return-1};c.range=function(a,c,b){1>=arguments.length&&(c=a||0,a=0);b=b||1;for(var d=Math.max(Math.ceil((c-a)/b),0),h=Array(d),f=0;d>f;f++,a+=b)h[f]=a;return h};var y=function(){};c.bind=function(a,b){var g,d;if(w&&a.bind===w)return w.apply(a,k.call(arguments,1));if(!c.isFunction(a))throw new TypeError("Bind must be called on a function");
return g=k.call(arguments,2),d=function(){if(!(this instanceof d))return a.apply(b,g.concat(k.call(arguments)));y.prototype=a.prototype;var h=new y;y.prototype=null;var f=a.apply(h,g.concat(k.call(arguments)));return c.isObject(f)?f:h}};c.partial=function(a){var b=k.call(arguments,1);return function(){for(var g=0,d=b.slice(),h=0,f=d.length;f>h;h++)d[h]===c&&(d[h]=arguments[g++]);for(;g<arguments.length;)d.push(arguments[g++]);return a.apply(this,d)}};c.bindAll=function(a){var b,g,d=arguments.length;
if(1>=d)throw Error("bindAll must be passed function names");for(b=1;d>b;b++)g=arguments[b],a[g]=c.bind(a[g],a);return a};c.memoize=function(a,b){var g=function(d){var h=g.cache,f=b?b.apply(this,arguments):d;return c.has(h,f)||(h[f]=a.apply(this,arguments)),h[f]};return g.cache={},g};c.delay=function(a,c){var b=k.call(arguments,2);return setTimeout(function(){return a.apply(null,b)},c)};c.defer=function(a){return c.delay.apply(c,[a,1].concat(k.call(arguments,1)))};c.throttle=function(a,b,d){var f,
h,x,m=null,k=0;d||(d={});var l=function(){k=!1===d.leading?0:c.now();m=null;x=a.apply(f,h);m||(f=h=null)};return function(){var p=c.now();k||!1!==d.leading||(k=p);var n=b-(p-k);return f=this,h=arguments,0>=n||n>b?(clearTimeout(m),m=null,k=p,x=a.apply(f,h),m||(f=h=null)):m||!1===d.trailing||(m=setTimeout(l,n)),x}};c.debounce=function(a,b,d){var f,h,k,m,l,p=function(){var n=c.now()-m;b>n&&0<n?f=setTimeout(p,b-n):(f=null,d||(l=a.apply(k,h),f||(k=h=null)))};return function(){k=this;h=arguments;m=c.now();
var n=d&&!f;return f||(f=setTimeout(p,b)),n&&(l=a.apply(k,h),k=h=null),l}};c.wrap=function(a,b){return c.partial(b,a)};c.negate=function(a){return function(){return!a.apply(this,arguments)}};c.compose=function(){var a=arguments,c=a.length-1;return function(){for(var b=c,d=a[c].apply(this,arguments);b--;)d=a[b].call(this,d);return d}};c.after=function(a,c){return function(){return 1>--a?c.apply(this,arguments):void 0}};c.before=function(a,c){var b;return function(){return 0<--a?b=c.apply(this,arguments):
c=null,b}};c.once=c.partial(c.before,2);c.keys=function(a){if(!c.isObject(a))return[];if(D)return D(a);var b=[],d;for(d in a)c.has(a,d)&&b.push(d);return b};c.values=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=a[b[h]];return f};c.pairs=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=[b[h],a[b[h]]];return f};c.invert=function(a){for(var b={},d=c.keys(a),f=0,h=d.length;h>f;f++)b[a[d[f]]]=d[f];return b};c.functions=c.methods=function(a){var b=[],d;for(d in a)c.isFunction(a[d])&&
b.push(d);return b.sort()};c.extend=function(a){if(!c.isObject(a))return a;for(var b,d,f=1,h=arguments.length;h>f;f++)for(d in b=arguments[f],b)C.call(b,d)&&(a[d]=b[d]);return a};c.pick=function(a,b,d){var f,h={};if(null==a)return h;if(c.isFunction(b))for(f in b=t(b,d),a){var l=a[f];b(l,f,a)&&(h[f]=l)}else{l=n.apply([],k.call(arguments,1));a=Object(a);for(var m=0,p=l.length;p>m;m++)f=l[m],f in a&&(h[f]=a[f])}return h};c.omit=function(a,b,d){if(c.isFunction(b))b=c.negate(b);else{var f=c.map(n.apply([],
k.call(arguments,1)),String);b=function(a,e){return!c.contains(f,e)}}return c.pick(a,b,d)};c.defaults=function(a){if(!c.isObject(a))return a;for(var b=1,d=arguments.length;d>b;b++){var f=arguments[b],h;for(h in f)void 0===a[h]&&(a[h]=f[h])}return a};c.clone=function(a){return c.isObject(a)?c.isArray(a)?a.slice():c.extend({},a):a};c.tap=function(a,b){return b(a),a};var z=function(a,b,d,f){if(a===b)return 0!==a||1/a===1/b;if(null==a||null==b)return a===b;a instanceof c&&(a=a._wrapped);b instanceof c&&
(b=b._wrapped);var h=p.call(a);if(h!==p.call(b))return!1;switch(h){case "[object RegExp]":case "[object String]":return""+a==""+b;case "[object Number]":return+a!==+a?+b!==+b:0===+a?1/+a===1/b:+a===+b;case "[object Date]":case "[object Boolean]":return+a===+b}if("object"!=typeof a||"object"!=typeof b)return!1;for(var k=d.length;k--;)if(d[k]===a)return f[k]===b;var k=a.constructor,m=b.constructor;if(k!==m&&"constructor"in a&&"constructor"in b&&!(c.isFunction(k)&&k instanceof k&&c.isFunction(m)&&m instanceof
m))return!1;d.push(a);f.push(b);var l;if("[object Array]"===h){if(l=a.length,h=l===b.length)for(;l--&&(h=z(a[l],b[l],d,f)););}else{var n,k=c.keys(a);if(l=k.length,h=c.keys(b).length===l)for(;l--&&(n=k[l],h=c.has(b,n)&&z(a[n],b[n],d,f)););}return d.pop(),f.pop(),h};c.isEqual=function(a,b){return z(a,b,[],[])};c.isEmpty=function(a){if(null==a)return!0;if(c.isArray(a)||c.isString(a)||c.isArguments(a))return 0===a.length;for(var b in a)if(c.has(a,b))return!1;return!0};c.isElement=function(a){return!(!a||
1!==a.nodeType)};c.isArray=f||function(a){return"[object Array]"===p.call(a)};c.isObject=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a};c.each("Arguments Function String Number Date RegExp".split(" "),function(a){c["is"+a]=function(b){return p.call(b)==="[object "+a+"]"}});c.isArguments(arguments)||(c.isArguments=function(a){return c.has(a,"callee")});"function"!=typeof/./&&(c.isFunction=function(a){return"function"==typeof a||!1});c.isFinite=function(a){return isFinite(a)&&!isNaN(parseFloat(a))};
c.isNaN=function(a){return c.isNumber(a)&&a!==+a};c.isBoolean=function(a){return!0===a||!1===a||"[object Boolean]"===p.call(a)};c.isNull=function(a){return null===a};c.isUndefined=function(a){return void 0===a};c.has=function(a,b){return null!=a&&C.call(a,b)};c.noConflict=function(){return a._=b,this};c.identity=function(a){return a};c.constant=function(a){return function(){return a}};c.noop=function(){};c.property=function(a){return function(b){return b[a]}};c.matches=function(a){var b=c.pairs(a),
d=b.length;return function(a){if(null==a)return!d;a=Object(a);for(var c=0;d>c;c++){var e=b[c],f=e[0];if(e[1]!==a[f]||!(f in a))return!1}return!0}};c.times=function(a,b,c){var d=Array(Math.max(0,a));b=t(b,c,1);for(c=0;a>c;c++)d[c]=b(c);return d};c.random=function(a,b){return null==b&&(b=a,a=0),a+Math.floor(Math.random()*(b-a+1))};c.now=Date.now||function(){return(new Date).getTime()};var f={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},u=c.invert(f),E=function(a){var b=
function(b){return a[b]},d="(?:"+c.keys(a).join("|")+")",f=RegExp(d),h=RegExp(d,"g");return function(a){return a=null==a?"":""+a,f.test(a)?a.replace(h,b):a}};c.escape=E(f);c.unescape=E(u);c.result=function(a,b){if(null!=a){var d=a[b];return c.isFunction(d)?a[b]():d}};var F=0;c.uniqueId=function(a){var b=++F+"";return a?a+b:b};c.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var A=/(.)^/,G={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028",
"\u2029":"u2029"},H=/\\|'|\r|\n|\u2028|\u2029/g,I=function(a){return"\\"+G[a]};c.template=function(a,b,d){!b&&d&&(b=d);b=c.defaults({},b,c.templateSettings);d=RegExp([(b.escape||A).source,(b.interpolate||A).source,(b.evaluate||A).source].join("|")+"|$","g");var f=0,h="__p+='";a.replace(d,function(b,c,d,g,k){return h+=a.slice(f,k).replace(H,I),f=k+b.length,c?h+="'+\n((__t=("+c+"))==null?'':_.escape(__t))+\n'":d?h+="'+\n((__t=("+d+"))==null?'':__t)+\n'":g&&(h+="';\n"+g+"\n__p+='"),b});h+="';\n";b.variable||
(h="with(obj||{}){\n"+h+"}\n");h="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+h+"return __p;\n";try{var k=new Function(b.variable||"obj","_",h)}catch(l){throw l.source=h,l;}d=function(a){return k.call(this,a,c)};return d.source="function("+(b.variable||"obj")+"){\n"+h+"}",d};c.chain=function(a){a=c(a);return a._chain=!0,a};var B=function(a){return this._chain?c(a).chain():a};c.mixin=function(a){c.each(c.functions(a),function(b){var d=c[b]=a[b];c.prototype[b]=
function(){var a=[this._wrapped];return l.apply(a,arguments),B.call(this,d.apply(c,a))}})};c.mixin(c);c.each("pop push reverse shift sort splice unshift".split(" "),function(a){var b=d[a];c.prototype[a]=function(){var c=this._wrapped;return b.apply(c,arguments),"shift"!==a&&"splice"!==a||0!==c.length||delete c[0],B.call(this,c)}});c.each(["concat","join","slice"],function(a){var b=d[a];c.prototype[a]=function(){return B.call(this,b.apply(this._wrapped,arguments))}});c.prototype.value=function(){return this._wrapped};
"function"==typeof define&&define.amd&&define("underscore",[],function(){return c})}).call(this);for(var BASE_64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",BASE_64_VALS={},i=0;i<BASE_64_CHARS.length;i++)BASE_64_VALS[BASE_64_CHARS.charAt(i)]=i;
Base64={encode:function(a){if("string"===typeof a){var b=a;a=Base64.newBinary(b.length);for(var d=0;d<b.length;d++){var f=b.charCodeAt(d);if(255<f)throw Error("Not ascii. Base64.encode can only take ascii strings.");a[d]=f}}for(var b=[],l=f=null,k=null,n=null,d=0;d<a.length;d++)switch(d%3){case 0:f=a[d]>>2&63;l=(a[d]&3)<<4;break;case 1:l|=a[d]>>4&15;k=(a[d]&15)<<2;break;case 2:k|=a[d]>>6&3,n=a[d]&63,b.push(getChar(f)),b.push(getChar(l)),b.push(getChar(k)),b.push(getChar(n)),n=k=l=f=null}null!=f&&
(b.push(getChar(f)),b.push(getChar(l)),null==k?b.push("="):b.push(getChar(k)),null==n&&b.push("="));return b.join("")}};var getChar=function(a){return BASE_64_CHARS.charAt(a)},getVal=function(a){return"="===a?-1:BASE_64_VALS[a]};Base64.newBinary=function(a){if("undefined"===typeof Uint8Array||"undefined"===typeof ArrayBuffer){for(var b=[],d=0;d<a;d++)b.push(0);b.$Uint8ArrayPolyfill=!0;return b}return new Uint8Array(new ArrayBuffer(a))};
Base64.decode=function(a){var b=Math.floor(3*a.length/4);"="==a.charAt(a.length-1)&&(b--,"="==a.charAt(a.length-2)&&b--);for(var b=Base64.newBinary(b),d=null,f=null,l=null,k=0,n=0;n<a.length;n++){var p=a.charAt(n),p=getVal(p);switch(n%4){case 0:if(0>p)throw Error("invalid base64 string");d=p<<2;break;case 1:if(0>p)throw Error("invalid base64 string");d|=p>>4;b[k++]=d;f=(p&15)<<4;break;case 2:0<=p&&(f|=p>>2,b[k++]=f,l=(p&3)<<6);break;case 3:0<=p&&(b[k++]=l|p)}}return b};EJSON={};EJSONTest={};
var customTypes={};EJSON.addType=function(a,b){if(_.has(customTypes,a))throw Error("Type "+a+" already present");customTypes[a]=b};
var isInfOrNan=function(a){return _.isNaN(a)||Infinity===a||-Infinity===a},builtinConverters=[{matchJSONValue:function(a){return _.has(a,"$date")&&1===_.size(a)},matchObject:function(a){return a instanceof Date},toJSONValue:function(a){return{$date:a.getTime()}},fromJSONValue:function(a){return new Date(a.$date)}},{matchJSONValue:function(a){return _.has(a,"$InfNaN")&&1===_.size(a)},matchObject:isInfOrNan,toJSONValue:function(a){return{$InfNaN:_.isNaN(a)?0:Infinity===a?1:-1}},fromJSONValue:function(a){return a.$InfNaN/
0}},{matchJSONValue:function(a){return _.has(a,"$binary")&&1===_.size(a)},matchObject:function(a){return"undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&_.has(a,"$Uint8ArrayPolyfill")},toJSONValue:function(a){return{$binary:Base64.encode(a)}},fromJSONValue:function(a){return Base64.decode(a.$binary)}},{matchJSONValue:function(a){return _.has(a,"$escape")&&1===_.size(a)},matchObject:function(a){return _.isEmpty(a)||2<_.size(a)?!1:_.any(builtinConverters,function(b){return b.matchJSONValue(a)})},
toJSONValue:function(a){var b={};_.each(a,function(a,f){b[f]=EJSON.toJSONValue(a)});return{$escape:b}},fromJSONValue:function(a){var b={};_.each(a.$escape,function(a,f){b[f]=EJSON.fromJSONValue(a)});return b}},{matchJSONValue:function(a){return _.has(a,"$type")&&_.has(a,"$value")&&2===_.size(a)},matchObject:function(a){return EJSON._isCustomType(a)},toJSONValue:function(a){var b=Meteor._noYieldsAllowed(function(){return a.toJSONValue()});return{$type:a.typeName(),$value:b}},fromJSONValue:function(a){var b=
a.$type;if(!_.has(customTypes,b))throw Error("Custom EJSON type "+b+" is not defined");var d=customTypes[b];return Meteor._noYieldsAllowed(function(){return d(a.$value)})}}];EJSON._isCustomType=function(a){return a&&"function"===typeof a.toJSONValue&&"function"===typeof a.typeName&&_.has(customTypes,a.typeName())};
var adjustTypesToJSONValue=EJSON._adjustTypesToJSONValue=function(a){if(null===a)return null;var b=toJSONValueHelper(a);if(void 0!==b)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b||void 0===b||isInfOrNan(b)){var l=toJSONValueHelper(b);l?a[f]=l:adjustTypesToJSONValue(b)}});return a},toJSONValueHelper=function(a){for(var b=0;b<builtinConverters.length;b++){var d=builtinConverters[b];if(d.matchObject(a))return d.toJSONValue(a)}};
EJSON.toJSONValue=function(a){var b=toJSONValueHelper(a);if(void 0!==b)return b;"object"===typeof a&&(a=EJSON.clone(a),adjustTypesToJSONValue(a));return a};
var adjustTypesFromJSONValue=EJSON._adjustTypesFromJSONValue=function(a){if(null===a)return null;var b=fromJSONValueHelper(a);if(b!==a)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b){var l=fromJSONValueHelper(b);b!==l?a[f]=l:adjustTypesFromJSONValue(b)}});return a},fromJSONValueHelper=function(a){if("object"===typeof a&&null!==a&&2>=_.size(a)&&_.all(a,function(a,b){return"string"===typeof b&&"$"===b.substr(0,1)}))for(var b=0;b<builtinConverters.length;b++){var d=
builtinConverters[b];if(d.matchJSONValue(a))return d.fromJSONValue(a)}return a};EJSON.fromJSONValue=function(a){var b=fromJSONValueHelper(a);return b===a&&"object"===typeof a?(a=EJSON.clone(a),adjustTypesFromJSONValue(a),a):b};EJSON.stringify=function(a,b){var d=EJSON.toJSONValue(a);return b&&(b.canonical||b.indent)?EJSON._canonicalStringify(d,b):JSON.stringify(d)};EJSON.parse=function(a){if("string"!==typeof a)throw Error("EJSON.parse argument should be a string");return EJSON.fromJSONValue(JSON.parse(a))};
EJSON.isBinary=function(a){return!!("undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&a.$Uint8ArrayPolyfill)};
EJSON.equals=function(a,b,d){var f,l=!(!d||!d.keyOrderSensitive);if(a===b||_.isNaN(a)&&_.isNaN(b))return!0;if(!a||!b||"object"!==typeof a||"object"!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.valueOf()===b.valueOf();if(EJSON.isBinary(a)&&EJSON.isBinary(b)){if(a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(a[f]!==b[f])return!1;return!0}if("function"===typeof a.equals)return a.equals(b,d);if("function"===typeof b.equals)return b.equals(a,d);if(a instanceof Array){if(!(b instanceof
Array)||a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(!EJSON.equals(a[f],b[f],d))return!1;return!0}switch(EJSON._isCustomType(a)+EJSON._isCustomType(b)){case 1:return!1;case 2:return EJSON.equals(EJSON.toJSONValue(a),EJSON.toJSONValue(b))}if(l){var k=[];_.each(b,function(a,b){k.push(b)});f=0;return(a=_.all(a,function(a,l){if(f>=k.length||l!==k[f]||!EJSON.equals(a,b[k[f]],d))return!1;f++;return!0}))&&f===k.length}f=0;return(a=_.all(a,function(a,k){if(!_.has(b,k)||!EJSON.equals(a,b[k],d))return!1;
f++;return!0}))&&_.size(b)===f};
EJSON.clone=function(a){var b;if("object"!==typeof a)return a;if(null===a)return null;if(a instanceof Date)return new Date(a.getTime());if(a instanceof RegExp)return a;if(EJSON.isBinary(a)){b=EJSON.newBinary(a.length);for(var d=0;d<a.length;d++)b[d]=a[d];return b}if(_.isArray(a)||_.isArguments(a)){b=[];for(d=0;d<a.length;d++)b[d]=EJSON.clone(a[d]);return b}if("function"===typeof a.clone)return a.clone();if(EJSON._isCustomType(a))return EJSON.fromJSONValue(EJSON.clone(EJSON.toJSONValue(a)),!0);b={};
_.each(a,function(a,d){b[d]=EJSON.clone(a)});return b};EJSON.newBinary=Base64.newBinary;Meteor={isClient:!0,active:!1,currentComputation:null};
var setCurrentComputation=function(a){Meteor.currentComputation=a;Meteor.active=!!a},_debugFunc=function(){return"undefined"!==typeof Meteor?Meteor._debug:"undefined"!==typeof console&&console.log?function(){console.log.apply(console,arguments)}:function(){}},_throwOrLog=function(a,b){if(throwFirstError)throw b;var d;b.stack&&b.message?(d=b.stack.indexOf(b.message),d=0<=d&&10>=d?b.stack:b.message+("\n"===b.stack.charAt(0)?"":"\n")+b.stack):d=b.stack||b.message;_debugFunc()("Exception from Meteor "+
a+" function:",d)},withNoYieldsAllowed=function(a){return"undefined"===typeof Meteor||Meteor.isClient?a:function(){var b=arguments;Meteor._noYieldsAllowed(function(){a.apply(null,b)})}},nextId=1,pendingComputations=[],willFlush=!1,inFlush=!1,inCompute=!1,throwFirstError=!1,afterFlushCallbacks=[],requireFlush=function(){willFlush||(setTimeout(Meteor.flush,0),willFlush=!0)},constructingComputation=!1;
Meteor.Computation=function(a,b){if(!constructingComputation)throw Error("Meteor.Computation constructor is private; use Meteor.run");this.invalidated=this.stopped=constructingComputation=!1;this.firstRun=!0;this._id=nextId++;this._onInvalidateCallbacks=[];this._parent=b;this._func=a;this._recomputing=!1;var d=!0;try{this._compute(),d=!1}finally{this.firstRun=!1,d&&this.stop()}};
Meteor.Computation.prototype.onInvalidate=function(a){var b=this;if("function"!==typeof a)throw Error("onInvalidate requires a function");b.invalidated?Meteor.nonreactive(function(){withNoYieldsAllowed(a)(b)}):b._onInvalidateCallbacks.push(a)};
Meteor.Computation.prototype.invalidate=function(){var a=this;if(!a.invalidated){a._recomputing||a.stopped||(requireFlush(),pendingComputations.push(this));a.invalidated=!0;for(var b=0,d;d=a._onInvalidateCallbacks[b];b++)Meteor.nonreactive(function(){withNoYieldsAllowed(d)(a)});a._onInvalidateCallbacks=[]}};Meteor.Computation.prototype.stop=function(){this.stopped||(this.stopped=!0,this.invalidate())};
Meteor.Computation.prototype._compute=function(){this.invalidated=!1;var a=Meteor.currentComputation;setCurrentComputation(this);inCompute=!0;try{withNoYieldsAllowed(this._func)(this)}finally{setCurrentComputation(a),inCompute=!1}};Meteor.Computation.prototype._recompute=function(){this._recomputing=!0;try{for(;this.invalidated&&!this.stopped;)try{this._compute()}catch(a){_throwOrLog("recompute",a)}}finally{this._recomputing=!1}};Meteor.Dependency=function(){this._dependentsById={}};
Meteor.Dependency.prototype.depend=function(a){if(!a){if(!Meteor.active)return!1;a=Meteor.currentComputation}var b=this,d=a._id;return d in b._dependentsById?!1:(b._dependentsById[d]=a,a.onInvalidate(function(){delete b._dependentsById[d]}),!0)};Meteor.Dependency.prototype.changed=function(){for(var a in this._dependentsById)this._dependentsById[a].invalidate()};Meteor.Dependency.prototype.hasDependents=function(){for(var a in this._dependentsById)return!0;return!1};
Meteor.flush=function(a){if(inFlush)throw Error("Can't call Meteor.flush while flushing");if(inCompute)throw Error("Can't flush inside Meteor.run");willFlush=inFlush=!0;throwFirstError=!(!a||!a._throwFirstError);a=!1;try{for(;pendingComputations.length||afterFlushCallbacks.length;){for(;pendingComputations.length;)pendingComputations.shift()._recompute();if(afterFlushCallbacks.length){var b=afterFlushCallbacks.shift();try{b()}catch(d){_throwOrLog("afterFlush",d)}}}a=!0}finally{a||(inFlush=!1,Meteor.flush({_throwFirstError:!1})),
inFlush=willFlush=!1}};Meteor.run=function(a){if("function"!==typeof a)throw Error("Meteor.run requires a function argument");constructingComputation=!0;var b=new Meteor.Computation(a,Meteor.currentComputation);if(Meteor.active)Meteor.onInvalidate(function(){b.stop()});return b};Meteor.nonreactive=function(a){var b=Meteor.currentComputation;setCurrentComputation(null);try{return a()}finally{setCurrentComputation(b)}};
Meteor.onInvalidate=function(a){if(!Meteor.active)throw Error("Meteor.onInvalidate requires a currentComputation");Meteor.currentComputation.onInvalidate(a)};Meteor.afterFlush=function(a){afterFlushCallbacks.push(a);requireFlush()};var stringify=function(a){return void 0===a?"undefined":EJSON.stringify(a)},parse=function(a){return void 0===a||"undefined"===a?void 0:EJSON.parse(a)};ReactiveMap=function(a){this.keys=a||{};this.keyDeps={};this.keyValueDeps={}};
_.extend(ReactiveMap.prototype,{set:function(a,b){b=stringify(b);var d="undefined";_.has(this.keys,a)&&(d=this.keys[a]);if(b!==d){this.keys[a]=b;var f=this.keyDeps[a];f&&f.changed();this.keyValueDeps[a]&&((d=this.keyValueDeps[a][d])&&d.changed(),(d=this.keyValueDeps[a][b])&&d.changed())}},setDefault:function(a,b){void 0===this.keys[a]&&this.set(a,b)},get:function(a){this._ensureKey(a);this.keyDeps[a].depend();return parse(this.keys[a])},equals:function(a,b){var d=this,f=Package["mongo-livedata"]&&
Meteor.Collection.ObjectID;if(!("string"===typeof b||"number"===typeof b||"boolean"===typeof b||"undefined"===typeof b||b instanceof Date||f&&b instanceof f)&&null!==b)throw Error("ReactiveMap.equals: value must be scalar");var l=stringify(b);if(Meteor.active&&(d._ensureKey(a),_.has(d.keyValueDeps[a],l)||(d.keyValueDeps[a][l]=new Meteor.Dependency),d.keyValueDeps[a][l].depend()))Meteor.onInvalidate(function(){d.keyValueDeps[a][l].hasDependents()||delete d.keyValueDeps[a][l]});f=void 0;_.has(d.keys,
a)&&(f=parse(d.keys[a]));return EJSON.equals(f,b)},_ensureKey:function(a){a in this.keyDeps||(this.keyDeps[a]=new Meteor.Dependency,this.keyValueDeps[a]={})},getMigrationData:function(){return this.keys}});ReactiveVar=function(a,b){if(!(this instanceof ReactiveVar))return new ReactiveVar(a,b);this.curValue=a;this.equalsFunc=b;this.dep=new Meteor.Dependency};ReactiveVar._isEqual=function(a,b){return a!==b?!1:!a||"number"===typeof a||"boolean"===typeof a||"string"===typeof a};
ReactiveVar.prototype.get=function(){Meteor.active&&this.dep.depend();return this.curValue};ReactiveVar.prototype.set=function(a){(this.equalsFunc||ReactiveVar._isEqual)(this.curValue,a)||(this.curValue=a,this.dep.changed())};ReactiveVar.prototype.toString=function(){return"ReactiveVar{"+this.get()+"}"};ReactiveVar.prototype._numListeners=function(){var a=0,b;for(b in this.dep._dependentsById)a++;return a};
ReactiveObject=function(a){var b;this._definePrivateProperty("_items",{});this._definePrivateProperty("_itemsMeteor",{});b=this;_.isArray(a)&&_.each(a,function(a){return b.defineProperty(a,void 0)});_.isObject(a)&&_.each(a,function(a,f){return b.defineProperty(f,a)})};
ReactiveObject.prototype.wrapArrayMethods=function(a,b){var d=this;_.each("pop push reverse shift sort slice unshift splice".split(" "),function(f){b[f]=function(){d._itemsMeteor[a].changed();return Array.prototype[f].apply(this,arguments)}});b.clean=function(){return _.filter(this,function(a){return!Match.test(a,Function)})};return b};
ReactiveObject.prototype.defineProperty=function(a,b){Object.defineProperty(this,a,{configurable:!0,enumerable:!0,get:_.bind(this._propertyGet,this,a),set:_.bind(this._propertySet,this,a)});this[a]=b;return this};ReactiveObject.prototype.undefineProperty=function(a){var b;b=this._itemsMeteor[a];delete this[a];delete this._items[a];delete this._itemsMeteor[a];b&&b.changed();return this};ReactiveObject.prototype.clone=function(){return new ReactiveObject(_.clone(this._items))};
ReactiveObject.prototype.equals=function(a){return null!=a&&a instanceof ReactiveObject&&_.isEqual(a._items,this._items)};ReactiveObject.prototype.typeName=function(){return"reactive-object"};ReactiveObject.prototype.toJSONValue=function(){return EJSON.toJSONValue(this._items)};
ReactiveObject.prototype._propertySet=function(a,b){var d,f;_.isArray(b)&&(b=this.wrapArrayMethods(a,b));this._items[a]=b;null==(d=this._itemsMeteor)[a]&&(d[a]=new Meteor.Dependency);null!=(f=this._itemsMeteor[a])&&f.changed();return this._items[a]};ReactiveObject.prototype._propertyGet=function(a){this._itemsMeteor[a].depend();return this._items[a]};ReactiveObject.prototype._definePrivateProperty=function(a,b){return Object.defineProperty(this,a,{configurable:!0,enumerable:!1,writable:!0,value:b})};
EJSON.addType("reactive-object",function(a){return new ReactiveObject(a)}); |
src/components/shared/screen-description.js | gabrielecker/animapp | import React, { Component } from 'react';
import { Container } from 'semantic-ui-react';
export default class ScreenDescription extends Component {
render() {
return (
<Container text>
{this.props.children}
</Container>
);
}
}
ScreenDescription.propTypes = {
children: React.PropTypes.string.isRequired,
};
|
pootle/static/js/user/components/UserProfileForm.js | pavels/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import { link } from 'autolinker';
import React from 'react';
import FormElement from 'components/FormElement';
import ModelFormMixin from 'mixins/ModelFormMixin';
import Avatar from 'components/Avatar';
// XXX: should probably live somewhere else
function linkify(input) {
return {
__html: link(input),
};
}
export const UserProfileForm = React.createClass({
propTypes: {
onDirty: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
},
mixins: [ModelFormMixin],
/* Lifecycle */
componentWillUpdate(nextProps, nextState) {
if (nextState.isDirty !== this.state.isDirty) {
this.props.onDirty(nextState.isDirty);
}
},
fields: ['full_name', 'twitter', 'linkedin', 'website', 'bio'],
/* Handlers */
handleSuccess(user) {
this.props.onSuccess(user);
},
/* Layout */
render() {
const model = this.getResource();
const { errors } = this.state;
const { formData } = this.state;
const avatarHelpMsg = gettext(
'To set or change your avatar for your email address ' +
'(%(email)s), please go to gravatar.com.'
);
const avatarHelp = interpolate(avatarHelpMsg, { email: model.get('email') },
true);
return (
<form
method="post"
id="item-form"
autoComplete="off"
onSubmit={this.handleFormSubmit}
>
<div className="fields">
<FormElement
label={gettext('Full Name')}
placeholder={gettext('Your Full Name')}
autoFocus
handleChange={this.handleChange}
name="full_name"
errors={errors.full_name}
value={formData.full_name}
/>
<p>
<label>{gettext('Avatar')}</label>
<Avatar email={model.get('email')} size={48} />
<span
className="helptext"
dangerouslySetInnerHTML={linkify(avatarHelp)}
/>
</p>
<p className="divider" />
<FormElement
label={gettext('Twitter')}
handleChange={this.handleChange}
placeholder={gettext('Your Twitter username')}
maxLength="15"
name="twitter"
errors={errors.twitter}
value={formData.twitter}
/>
<FormElement
label={gettext('LinkedIn')}
handleChange={this.handleChange}
placeholder={gettext('Your LinkedIn profile URL')}
name="linkedin"
errors={errors.linkedin}
value={formData.linkedin}
/>
<FormElement
label={gettext('Website')}
handleChange={this.handleChange}
placeholder={gettext('Your Personal website/blog URL')}
name="website"
errors={errors.website}
value={formData.website}
/>
<FormElement
type="textarea"
label={gettext('Short Bio')}
handleChange={this.handleChange}
placeholder={gettext('Why are you part of our translation project? ' +
'Describe yourself, inspire others!')}
name="bio"
errors={errors.bio}
value={formData.bio}
/>
</div>
<p className="buttons">
<input
type="submit"
className="btn btn-primary"
disabled={!this.state.isDirty}
value={gettext('Save')}
/>
</p>
</form>
);
},
});
export default UserProfileForm;
|
src/components/DaySelectionRenderer.js | corragon/six | import React, { Component } from 'react';
import {
StyleSheet,
ScrollView,
Text,
} from 'react-native';
import {attach, depend, dependency} from 'react-ringa';
import AppModel from '../global/AppModel';
import DayBadge from './DayBadge';
export default class DaySelectionRenderer extends Component {
constructor(props) {
super(props);
depend(this, dependency(AppModel, ['dayList']));
}
render() {
if (this.state.dayList) {
return (<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
automaticallyAdjustContentInsets={false}
horizontal={true}
style={styles.scrollView}>
{this.state.dayList.map((day, i) => <DayBadge key={i} day={day} />)}
</ScrollView>);
}
else {
return <Text style={styles.text}>Loading...</Text>;
}
}
}
const styles = StyleSheet.create({
text: {
fontSize: 20,
textAlign: 'center',
margin: 15,
},
scrollView: {
marginTop: 20,
flex: 10,
maxHeight: 128
},
horizontalScrollView: {
height: 50,
},
}); |
src/components/NavigationHeader.js | PedroAlvCha/ud918-readable | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { categoryListSet, fetchCategoryList } from '../actions/category_actions.js';
import keyIndex from 'react-key-index';
import { capitalize } from '../utils/helpers'
class NavBarInstance extends Component {
state = {
categoryList: [],
}
componentWillMount() {
this.props.categoryListFetch();
}
render(){
const { categoryList } = this.props
function handleSelect(selectedKey) {
alert('selected ' + selectedKey);
}
return(
<Navbar inverse collapseOnSelect defaultCollapsed>
<Navbar.Header>
<Navbar.Brand>
<a href="/">Readable</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav >
{categoryList.map((category,index) => (
<NavItem eventKey={index} key={index} id={index} href={"/"+category.path}>
<Link to={"/"+category.path}>{capitalize(category.name)}</Link>
</NavItem>
))}
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
function mapStateToProps (state, props) {
return {
categoryList: state.categoryManager.categoryList,
}
}
function mapDispatchToProps (dispatch) {
return {
categoryListFetch: (data) =>dispatch(fetchCategoryList(data)),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(NavBarInstance)
|
packages/material-ui-icons/src/StarHalf.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><defs><path id="a" d="M0 0h24v24H0V0z" /></defs><path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4V6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z" /></React.Fragment>
, 'StarHalf');
|
src/components/LineGraphComponents/LineGraphDisplay/index.js | dramich/twitchBot | import React, { Component } from 'react';
import Loader from '../../Loader';
import { emoColors, socColors } from '../descriptions';
import { styles } from './styles.scss';
export default class LineGraphDisplay extends Component {
constructor(props) {
super(props);
this.state = {
topRef: false,
btmRef: false,
windowWidth: window.innerWidth,
};
this.handleResize = this.handleResize.bind(this);
}
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
handleMouseEnter(line) {
if (line === 'top') this.setState({ topRef: true });
if (line === 'btm') this.setState({ btmRef: true });
}
handleMouseLeave(line) {
if (line === 'top') this.setState({ topRef: false });
if (line === 'btm') this.setState({ btmRef: false });
}
handleResize() {
this.setState({ windowWidth: window.innerWidth });
}
renderLines(colors, paths) {
if (!paths) return false;
const lines = [];
Object.keys(paths).forEach(key => {
lines.push(<path key={key} stroke={colors[key]} fill="none" d={paths[key]} />);
});
return (
<g>{lines}</g>
);
}
renderOutlines(paths) {
if (!paths) return false;
const outlines = [];
Object.keys(paths).forEach(key => {
outlines.push(<path key={key} stroke="#FFF" className="stroke-outline" fill="none" d={paths[key]} />);
});
return (
<g>{outlines}</g>
);
}
render() {
return (
<div className={`${styles}`}>
<div className="col-lg-12 line-graph-container">
{/* Reference Line Explanations */}
<div className={`graph-refs ${this.props.activeGraph === 'emotion' ? 'refs-active' : ''}`}>
<span className={`graph-explanation ${this.state.topRef ? 'visible' : ''}`}>Values above this line indicate that the chat is more likely to be perceived as conveying this emotion</span>
<span className={`graph-explanation ${this.state.btmRef ? 'visible' : ''}`}>Values below this line indicate that the chat is less likely to be perceived as conveying this emotion</span>
</div>
<div className={`graph-refs ${this.props.activeGraph === 'social' ? 'refs-active' : ''}`}>
<span className={`graph-explanation ${this.state.topRef ? 'visible' : ''}`}>Values above this line indicate that the chat sentiment is closely aligning with this social attribute</span>
<span className={`graph-explanation ${this.state.btmRef ? 'visible' : ''}`}>Values below this line indicate that the chat sentiment is more likely to be perceived as aligning with the opposite extreme of this attribute</span>
</div>
{/* Loading animation */}
<div className={`loader ${this.props.waitingForMsgs ? 'loader-active' : ''}`}>
<Loader key={this.state.windowWidth} />
</div>
{/* Main Graph */}
<svg width="100%" height="400" viewBox="0 0 400 100" preserveAspectRatio="none">
{/* Graph Backgrounds */}
<rect className={`graph-bg ${this.props.activeGraph === 'emotion' ? 'bg-active' : ''}`} id="emo-graph-bg" x="0" y="0" width="400" height="100" fill="#fff" fillOpacity="0" />
<rect className={`graph-bg ${this.props.activeGraph === 'social' ? 'bg-active' : ''}`} id="soc-graph-bg" x="0" y="0" width="400" height="100" fill="#fff" fillOpacity="0" />
{/* Graph Reference Lines and Boxes */}
<g className={`graph-refs ${this.props.activeGraph === 'emotion' ? 'refs-active' : ''}`}>
<path className="reference-line" d="M 0.3 25 l 399.7 0" />
<rect id="upper-ref" x="0" y="0" width="400" height="25" fill="#fff" className={`ref-box ${this.state.topRef ? 'visible' : ''}`} />
<path className="reference-line" d="M 0.3 50 l 399.7 0" />
<rect id="lower-ref" x="0" y="50" width="400" height="50" fill="#fff" className={`ref-box ${this.state.btmRef ? 'visible' : ''}`} />
</g>
<g className={`graph-refs ${this.props.activeGraph === 'social' ? 'refs-active' : ''}`}>
<path className="reference-line" d="M 0.3 25 l 399.7 0" />
<rect id="upper-ref" x="0" y="0" width="400" height="25" fill="#fff" className={`ref-box ${this.state.topRef ? 'visible' : ''}`} />
<path className="reference-line" d="M 0.3 75 l 399.7 0" />
<rect id="lower-ref" x="0" y="75" width="400" height="25" fill="#fff" className={`ref-box ${this.state.btmRef ? 'visible' : ''}`} />
</g>
{/* Graph Lines */}
<g id="line-container">
<g className={`graph-lines ${this.props.activeGraph === 'emotion' ? 'lines-active' : ''}`}>
{this.renderOutlines(this.props.emotionPaths)}
{this.renderLines(emoColors, this.props.emotionPaths)}
</g>
<g className={`graph-lines ${this.props.activeGraph === 'social' ? 'lines-active' : ''}`}>
{this.renderOutlines(this.props.socialPaths)}
{this.renderLines(socColors, this.props.socialPaths)}
</g>
</g>
{/* Reference Line Triggers (hovering brings up box and explanation) */}
<g className={`graph-refs ${this.props.activeGraph === 'emotion' ? 'refs-active' : ''}`}>
<path
className="reference-line-trigger"
stroke="transparent"
d="M 0.3 25 l 399.7 0"
onMouseEnter={() => this.handleMouseEnter('top')}
onMouseLeave={() => this.handleMouseLeave('top')}
/>
<path
className="reference-line-trigger"
stroke="transparent"
d="M 0.3 50 l 399.7 0"
onMouseEnter={() => this.handleMouseEnter('btm')}
onMouseLeave={() => this.handleMouseLeave('btm')}
/>
</g>
<g className={`graph-refs ${this.props.activeGraph === 'social' ? 'refs-active' : ''}`}>
<path
className="reference-line-trigger"
stroke="transparent"
d="M 0.3 25 l 399.7 0"
onMouseEnter={() => this.handleMouseEnter('top')}
onMouseLeave={() => this.handleMouseLeave('top')}
/>
<path
className="reference-line-trigger"
stroke="transparent"
d="M 0.3 75 l 399.7 0"
onMouseEnter={() => this.handleMouseEnter('btm')}
onMouseLeave={() => this.handleMouseLeave('btm')}
/>
</g>
</svg>
<span className="x-axis-label start">30 Sec<br />Ago</span>
<span className="x-axis-label end">Now</span>
{/* Loading message */}
<span className={`loader-msg ${this.props.waitingForMsgs ? 'loader-active' : ''}`}>
{`${this.props.firstToneIn && this.props.firstMsgIn ? 'This chat activity is. Slowing. Down...' : ''}`}
{`${!this.props.firstToneIn && this.props.firstMsgIn ? 'Here it comes...' : ''}`}
{`${!this.props.firstToneIn && !this.props.firstMsgIn ? 'Awaiting first transmission' : ''}`}
</span>
</div>
</div>
);
}
}
LineGraphDisplay.propTypes = {
activeGraph: React.PropTypes.string,
waitingForMsgs: React.PropTypes.bool,
firstMsgIn: React.PropTypes.bool,
firstToneIn: React.PropTypes.bool,
emotionPaths: React.PropTypes.object,
socialPaths: React.PropTypes.object,
};
|
ajax/libs/yui/3.15.0/event-custom-base/event-custom-base-debug.js | codevinsky/cdnjs | /*
YUI 3.15.0 (build 834026e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('event-custom-base', function (Y, NAME) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
Y.Env.evt = {
handles: {},
plugins: {}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* Allows for the insertion of methods that are executed before or after
* a specified method
* @class Do
* @static
*/
var DO_BEFORE = 0,
DO_AFTER = 1,
DO = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
* @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object
* replaces the role of this property, but is considered to be private, and
* is only mentioned to provide a migration path.
*
* If you have a use case which warrants migration to the _yuiaop property,
* please file a ticket to let us know what it's used for and we can see if
* we need to expose hooks for that functionality more formally.
*/
objs: null,
/**
* <p>Execute the supplied method before the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>
* <dd>Replace the arguments that the original function will be
* called with.</dd>
* <dt></code>Y.Do.Prevent(message)</code></dt>
* <dd>Don't execute the wrapped function. Other before phase
* wrappers will be executed.</dd>
* </dl>
*
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
// Y.log('Do before: ' + sFn, 'info', 'event');
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_BEFORE, f, obj, sFn);
},
/**
* <p>Execute the supplied method after the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>
* <dd>Return <code>returnValue</code> instead of the wrapped
* method's original return value. This can be further altered by
* other after phase wrappers.</dd>
* </dl>
*
* <p>The static properties <code>Y.Do.originalRetVal</code> and
* <code>Y.Do.currentRetVal</code> will be populated for reference.</p>
*
* @method after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return {string} handle for the subscription
* @static
*/
after: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_AFTER, f, obj, sFn);
},
/**
* Execute the supplied method before or after the specified function.
* Used by <code>before</code> and <code>after</code>.
*
* @method _inject
* @param when {string} before or after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @return {string} handle for the subscription
* @private
* @static
*/
_inject: function(when, fn, obj, sFn) {
// object id
var id = Y.stamp(obj), o, sid;
if (!obj._yuiaop) {
// create a map entry for the obj if it doesn't exist, to hold overridden methods
obj._yuiaop = {};
}
o = obj._yuiaop;
if (!o[sFn]) {
// create a map entry for the method if it doesn't exist
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
obj[sFn] = function() {
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
sid = id + Y.stamp(fn) + sFn;
// register the callback
o[sFn].register(sid, fn, when);
return new Y.EventHandle(o[sFn], sid);
},
/**
* Detach a before or after subscription.
*
* @method detach
* @param handle {string} the subscription handle
* @static
*/
detach: function(handle) {
if (handle.detach) {
handle.detach();
}
}
};
Y.Do = DO;
//////////////////////////////////////////////////////////////////////////
/**
* Contains the return value from the wrapped method, accessible
* by 'after' event listeners.
*
* @property originalRetVal
* @static
* @since 3.2.0
*/
/**
* Contains the current state of the return value, consumable by
* 'after' event listeners, and updated if an after subscriber
* changes the return value generated by the wrapped function.
*
* @property currentRetVal
* @static
* @since 3.2.0
*/
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
DO.Method = function(obj, sFn) {
this.obj = obj;
this.methodName = sFn;
this.method = obj[sFn];
this.before = {};
this.after = {};
};
/**
* Register a aop subscriber
* @method register
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype.register = function (sid, fn, when) {
if (when) {
this.after[sid] = fn;
} else {
this.before[sid] = fn;
}
};
/**
* Unregister a aop subscriber
* @method delete
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype._delete = function (sid) {
// Y.log('Y.Do._delete: ' + sid, 'info', 'Event');
delete this.before[sid];
delete this.after[sid];
};
/**
* <p>Execute the wrapped method. All arguments are passed into the wrapping
* functions. If any of the before wrappers return an instance of
* <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped
* function nor any after phase subscribers will be executed.</p>
*
* <p>The return value will be the return value of the wrapped function or one
* provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or
* <code>Y.Do.AlterReturn</code>.
*
* @method exec
* @param arg* {any} Arguments are passed to the wrapping and wrapped functions
* @return {any} Return value of wrapped function unless overwritten (see above)
*/
DO.Method.prototype.exec = function () {
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
for (i in bf) {
if (bf.hasOwnProperty(i)) {
ret = bf[i].apply(this.obj, args);
if (ret) {
switch (ret.constructor) {
case DO.Halt:
return ret.retVal;
case DO.AlterArgs:
args = ret.newArgs;
break;
case DO.Prevent:
prevented = true;
break;
default:
}
}
}
}
// execute method
if (!prevented) {
ret = this.method.apply(this.obj, args);
}
DO.originalRetVal = ret;
DO.currentRetVal = ret;
// execute after methods.
for (i in af) {
if (af.hasOwnProperty(i)) {
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
if (newRet && newRet.constructor === DO.Halt) {
return newRet.retVal;
// Check for a new return value
} else if (newRet && newRet.constructor === DO.AlterReturn) {
ret = newRet.newRetVal;
// Update the static retval state
DO.currentRetVal = ret;
}
}
}
return ret;
};
//////////////////////////////////////////////////////////////////////////
/**
* Return an AlterArgs object when you want to change the arguments that
* were passed into the function. Useful for Do.before subscribers. An
* example would be a service that scrubs out illegal characters prior to
* executing the core business logic.
* @class Do.AlterArgs
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newArgs {Array} Call parameters to be used for the original method
* instead of the arguments originally passed in.
*/
DO.AlterArgs = function(msg, newArgs) {
this.msg = msg;
this.newArgs = newArgs;
};
/**
* Return an AlterReturn object when you want to change the result returned
* from the core method to the caller. Useful for Do.after subscribers.
* @class Do.AlterReturn
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newRetVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.AlterReturn = function(msg, newRetVal) {
this.msg = msg;
this.newRetVal = newRetVal;
};
/**
* Return a Halt object when you want to terminate the execution
* of all subsequent subscribers as well as the wrapped method
* if it has not exectued yet. Useful for Do.before subscribers.
* @class Do.Halt
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.Halt = function(msg, retVal) {
this.msg = msg;
this.retVal = retVal;
};
/**
* Return a Prevent object when you want to prevent the wrapped function
* from executing, but want the remaining listeners to execute. Useful
* for Do.before subscribers.
* @class Do.Prevent
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
*/
DO.Prevent = function(msg) {
this.msg = msg;
};
/**
* Return an Error object when you want to terminate the execution
* of all subsequent method calls.
* @class Do.Error
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
* @deprecated use Y.Do.Halt or Y.Do.Prevent
*/
DO.Error = DO.Halt;
//////////////////////////////////////////////////////////////////////////
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
// var onsubscribeType = "_event:onsub",
var YArray = Y.Array,
AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
CONFIGS_HASH = YArray.hash(CONFIGS),
nativeSlice = Array.prototype.slice,
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log',
mixConfigs = function(r, s, ov) {
var p;
for (p in s) {
if (CONFIGS_HASH[p] && (ov || !(p in r))) {
r[p] = s[p];
}
}
return r;
};
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires.
* @param {object} defaults configuration object.
* @class CustomEvent
* @constructor
*/
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
/**
* By default all custom events are logged in the debug build, set silent
* to true to disable debug outpu for this event.
* @property silent
* @type boolean
*/
Y.CustomEvent = function(type, defaults) {
this._kds = Y.CustomEvent.keepDeprecatedSubs;
this.id = Y.guid();
this.type = type;
this.silent = this.logSystem = (type === YUI_LOG);
if (this._kds) {
/**
* The subscribers to this event
* @property subscribers
* @type Subscriber {}
* @deprecated
*/
/**
* 'After' subscribers
* @property afters
* @type Subscriber {}
* @deprecated
*/
this.subscribers = {};
this.afters = {};
}
if (defaults) {
mixConfigs(this, defaults, true);
}
};
/**
* Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a>
* and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance.
*
* These properties were changed to private properties (`_subscribers` and `_afters`), and
* converted from objects to arrays for performance reasons.
*
* Setting this property to true will populate the deprecated `subscribers` and `afters`
* properties for people who may be using them (which is expected to be rare). There will
* be a performance hit, compared to the new array based implementation.
*
* If you are using these deprecated properties for a use case which the public API
* does not support, please file an enhancement request, and we can provide an alternate
* public implementation which doesn't have the performance cost required to maintiain the
* properties as objects.
*
* @property keepDeprecatedSubs
* @static
* @for CustomEvent
* @type boolean
* @default false
* @deprecated
*/
Y.CustomEvent.keepDeprecatedSubs = false;
Y.CustomEvent.mixConfigs = mixConfigs;
Y.CustomEvent.prototype = {
constructor: Y.CustomEvent,
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
/**
* If 0, this event does not broadcast. If 1, the YUI instance is notified
* every time this event fires. If 2, the YUI instance and the YUI global
* (if event is enabled on the global) are notified every time this event
* fires.
* @property broadcast
* @type int
*/
/**
* Specifies whether this event should be queued when the host is actively
* processing an event. This will effect exectution order of the callbacks
* for the various events.
* @property queuable
* @type boolean
* @default false
*/
/**
* This event has fired if true
*
* @property fired
* @type boolean
* @default false;
*/
/**
* An array containing the arguments the custom event
* was last fired with.
* @property firedWith
* @type Array
*/
/**
* This event should only fire one time if true, and if
* it has fired, any new subscribers should be notified
* immediately.
*
* @property fireOnce
* @type boolean
* @default false;
*/
/**
* fireOnce listeners will fire syncronously unless async
* is set to true
* @property async
* @type boolean
* @default false
*/
/**
* Flag for stopPropagation that is modified during fire()
* 1 means to stop propagation to bubble targets. 2 means
* to also stop additional subscribers on this target.
* @property stopped
* @type int
*/
/**
* Flag for preventDefault that is modified during fire().
* if it is not 0, the default behavior for this event
* @property prevented
* @type int
*/
/**
* Specifies the host for this custom event. This is used
* to enable event bubbling
* @property host
* @type EventTarget
*/
/**
* The default function to execute after event listeners
* have fire, but only if the default action was not
* prevented.
* @property defaultFn
* @type Function
*/
/**
* Flag for the default function to execute only if the
* firing event is the current target. This happens only
* when using custom event delegation and setting the
* flag to `true` mimics the behavior of event delegation
* in the DOM.
*
* @property defaultTargetOnly
* @type Boolean
* @default false
*/
/**
* The function to execute if a subscriber calls
* stopPropagation or stopImmediatePropagation
* @property stoppedFn
* @type Function
*/
/**
* The function to execute if a subscriber calls
* preventDefault
* @property preventedFn
* @type Function
*/
/**
* The subscribers to this event
* @property _subscribers
* @type Subscriber []
* @private
*/
/**
* 'After' subscribers
* @property _afters
* @type Subscriber []
* @private
*/
/**
* If set to true, the custom event will deliver an EventFacade object
* that is similar to a DOM event object.
* @property emitFacade
* @type boolean
* @default false
*/
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
signature : YUI3_SIGNATURE,
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
context : Y,
/**
* Specifies whether or not this event's default function
* can be cancelled by a subscriber by executing preventDefault()
* on the event facade
* @property preventable
* @type boolean
* @default true
*/
preventable : true,
/**
* Specifies whether or not a subscriber can stop the event propagation
* via stopPropagation(), stopImmediatePropagation(), or halt()
*
* Events can only bubble if emitFacade is true.
*
* @property bubbles
* @type boolean
* @default true
*/
bubbles : true,
/**
* Returns the number of subscribers for this event as the sum of the on()
* subscribers and after() subscribers.
*
* @method hasSubs
* @return Number
*/
hasSubs: function(when) {
var s = 0,
a = 0,
subs = this._subscribers,
afters = this._afters,
sib = this.sibling;
if (subs) {
s = subs.length;
}
if (afters) {
a = afters.length;
}
if (sib) {
subs = sib._subscribers;
afters = sib._afters;
if (subs) {
s += subs.length;
}
if (afters) {
a += afters.length;
}
}
if (when) {
return (when === 'after') ? a : s;
}
return (s + a);
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('detach', 'attach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
this.monitored = true;
var type = this.id + '|' + this.type + '_' + what,
args = nativeSlice.call(arguments, 0);
args[0] = type;
return this.host.on.apply(this.host, args);
},
/**
* Get all of the subscribers to this event and any sibling event
* @method getSubs
* @return {Array} first item is the on subscribers, second the after.
*/
getSubs: function() {
var sibling = this.sibling,
subs = this._subscribers,
afters = this._afters,
siblingSubs,
siblingAfters;
if (sibling) {
siblingSubs = sibling._subscribers;
siblingAfters = sibling._afters;
}
if (siblingSubs) {
if (subs) {
subs = subs.concat(siblingSubs);
} else {
subs = siblingSubs.concat();
}
} else {
if (subs) {
subs = subs.concat();
} else {
subs = [];
}
}
if (siblingAfters) {
if (afters) {
afters = afters.concat(siblingAfters);
} else {
afters = siblingAfters.concat();
}
} else {
if (afters) {
afters = afters.concat();
} else {
afters = [];
}
}
return [subs, afters];
},
/**
* Apply configuration properties. Only applies the CONFIG whitelist
* @method applyConfig
* @param o hash of properties to apply.
* @param force {boolean} if true, properties that exist on the event
* will be overwritten.
*/
applyConfig: function(o, force) {
mixConfigs(this, o, force);
},
/**
* Create the Subscription for subscribing function, context, and bound
* arguments. If this is a fireOnce event, the subscriber is immediately
* notified.
*
* @method _on
* @param fn {Function} Subscription callback
* @param [context] {Object} Override `this` in the callback
* @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()
* @param [when] {String} "after" to slot into after subscribers
* @return {EventHandle}
* @protected
*/
_on: function(fn, context, args, when) {
if (!fn) { this.log('Invalid callback for CE: ' + this.type); }
var s = new Y.Subscriber(fn, context, args, when),
firedWith;
if (this.fireOnce && this.fired) {
firedWith = this.firedWith;
// It's a little ugly for this to know about facades,
// but given the current breakup, not much choice without
// moving a whole lot of stuff around.
if (this.emitFacade && this._addFacadeToArgs) {
this._addFacadeToArgs(firedWith);
}
if (this.async) {
setTimeout(Y.bind(this._notify, this, s, firedWith), 0);
} else {
this._notify(s, firedWith);
}
}
if (when === AFTER) {
if (!this._afters) {
this._afters = [];
}
this._afters.push(s);
} else {
if (!this._subscribers) {
this._subscribers = [];
}
this._subscribers.push(s);
}
if (this._kds) {
if (when === AFTER) {
this.afters[s.id] = s;
} else {
this.subscribers[s.id] = s;
}
}
return new Y.EventHandle(this, s);
},
/**
* Listen for this event
* @method subscribe
* @param {Function} fn The function to execute.
* @return {EventHandle} Unsubscribe handle.
* @deprecated use on.
*/
subscribe: function(fn, context) {
Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated');
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
return this._on(fn, context, a, true);
},
/**
* Listen for this event
* @method on
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} An object with a detach method to detch the handler(s).
*/
on: function(fn, context) {
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
if (this.monitored && this.host) {
this.host._monitor('attach', this, {
args: arguments
});
}
return this._on(fn, context, a, true);
},
/**
* Listen for this event after the normal subscribers have been notified and
* the default behavior has been applied. If a normal subscriber prevents the
* default behavior, it also prevents after listeners from firing.
* @method after
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} handle Unsubscribe handle.
*/
after: function(fn, context) {
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
return this._on(fn, context, a, AFTER);
},
/**
* Detach listeners.
* @method detach
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {Number} returns the number of subscribers unsubscribed.
*/
detach: function(fn, context) {
// unsubscribe handle
if (fn && fn.detach) {
return fn.detach();
}
var i, s,
found = 0,
subs = this._subscribers,
afters = this._afters;
if (subs) {
for (i = subs.length; i >= 0; i--) {
s = subs[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s, subs, i);
found++;
}
}
}
if (afters) {
for (i = afters.length; i >= 0; i--) {
s = afters[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s, afters, i);
found++;
}
}
}
return found;
},
/**
* Detach listeners.
* @method unsubscribe
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int|undefined} returns the number of subscribers unsubscribed.
* @deprecated use detach.
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Notify a single subscriber
* @method _notify
* @param {Subscriber} s the subscriber.
* @param {Array} args the arguments array to apply to the listener.
* @protected
*/
_notify: function(s, args, ef) {
this.log(this.type + '->' + 'sub: ' + s.id);
var ret;
ret = s.notify(args, this);
if (false === ret || this.stopped > 1) {
this.log(this.type + ' cancelled by subscriber');
return false;
}
return true;
},
/**
* Logger abstraction to centralize the application of the silent flag
* @method log
* @param {string} msg message to log.
* @param {string} cat log category.
*/
log: function(msg, cat) {
if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); }
},
/**
* Notifies the subscribers. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters:
* <ul>
* <li>The type of event</li>
* <li>All of the arguments fire() was executed with as an array</li>
* <li>The custom object (if any) that was passed into the subscribe()
* method</li>
* </ul>
* @method fire
* @param {Object*} arguments an arbitrary set of parameters to pass to
* the handler.
* @return {boolean} false if one of the subscribers returned false,
* true otherwise.
*
*/
fire: function() {
// push is the fastest way to go from arguments to arrays
// for most browsers currently
// http://jsperf.com/push-vs-concat-vs-slice/2
var args = [];
args.push.apply(args, arguments);
return this._fire(args);
},
/**
* Private internal implementation for `fire`, which is can be used directly by
* `EventTarget` and other event module classes which have already converted from
* an `arguments` list to an array, to avoid the repeated overhead.
*
* @method _fire
* @private
* @param {Array} args The array of arguments passed to be passed to handlers.
* @return {boolean} false if one of the subscribers returned false, true otherwise.
*/
_fire: function(args) {
if (this.fireOnce && this.fired) {
this.log('fireOnce event: ' + this.type + ' already fired');
return true;
} else {
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
this.fired = true;
if (this.fireOnce) {
this.firedWith = args;
}
if (this.emitFacade) {
return this.fireComplex(args);
} else {
return this.fireSimple(args);
}
}
},
/**
* Set up for notifying subscribers of non-emitFacade events.
*
* @method fireSimple
* @param args {Array} Arguments passed to fire()
* @return Boolean false if a subscriber returned false
* @protected
*/
fireSimple: function(args) {
this.stopped = 0;
this.prevented = 0;
if (this.hasSubs()) {
var subs = this.getSubs();
this._procSubs(subs[0], args);
this._procSubs(subs[1], args);
}
if (this.broadcast) {
this._broadcast(args);
}
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type);
args[0] = args[0] || {};
return this.fireSimple(args);
},
/**
* Notifies a list of subscribers.
*
* @method _procSubs
* @param subs {Array} List of subscribers
* @param args {Array} Arguments passed to fire()
* @param ef {}
* @return Boolean false if a subscriber returns false or stops the event
* propagation via e.stopPropagation(),
* e.stopImmediatePropagation(), or e.halt()
* @private
*/
_procSubs: function(subs, args, ef) {
var s, i, l;
for (i = 0, l = subs.length; i < l; i++) {
s = subs[i];
if (s && s.fn) {
if (false === this._notify(s, args, ef)) {
this.stopped = 2;
}
if (this.stopped === 2) {
return false;
}
}
}
return true;
},
/**
* Notifies the YUI instance if the event is configured with broadcast = 1,
* and both the YUI instance and Y.Global if configured with broadcast = 2.
*
* @method _broadcast
* @param args {Array} Arguments sent to fire()
* @private
*/
_broadcast: function(args) {
if (!this.stopped && this.broadcast) {
var a = args.concat();
a.unshift(this.type);
if (this.host !== Y) {
Y.fire.apply(Y, a);
}
if (this.broadcast === 2) {
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {Number} The number of listeners unsubscribed.
* @deprecated use detachAll.
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {Number} The number of listeners unsubscribed.
*/
detachAll: function() {
return this.detach();
},
/**
* Deletes the subscriber from the internal store of on() and after()
* subscribers.
*
* @method _delete
* @param s subscriber object.
* @param subs (optional) on or after subscriber array
* @param index (optional) The index found.
* @private
*/
_delete: function(s, subs, i) {
var when = s._when;
if (!subs) {
subs = (when === AFTER) ? this._afters : this._subscribers;
}
if (subs) {
i = YArray.indexOf(subs, s, 0);
if (s && subs[i] === s) {
subs.splice(i, 1);
}
}
if (this._kds) {
if (when === AFTER) {
delete this.afters[s.id];
} else {
delete this.subscribers[s.id];
}
}
if (this.monitored && this.host) {
this.host._monitor('detach', this, {
ce: this,
sub: s
});
}
if (s) {
s.deleted = true;
}
}
};
/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn The wrapped function to execute.
* @param {Object} context The value of the keyword 'this' in the listener.
* @param {Array} args* 0..n additional arguments to supply the listener.
*
* @class Subscriber
* @constructor
*/
Y.Subscriber = function(fn, context, args, when) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
this.id = Y.guid();
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
this.args = args;
this._when = when;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
Y.Subscriber.prototype = {
constructor: Y.Subscriber,
_notify: function(c, args, ce) {
if (this.deleted && !this.postponed) {
if (this.postponed) {
delete this.fn;
delete this.context;
} else {
delete this.postponed;
return null;
}
}
var a = this.args, ret;
switch (ce.signature) {
case 0:
ret = this.fn.call(c, ce.type, args, c);
break;
case 1:
ret = this.fn.call(c, args[0] || null, c);
break;
default:
if (a || args) {
args = args || [];
a = (a) ? args.concat(a) : args;
ret = this.fn.apply(c, a);
} else {
ret = this.fn.call(c);
}
}
if (this.once) {
ce._delete(this);
}
return ret;
},
/**
* Executes the subscriber.
* @method notify
* @param args {Array} Arguments array for the subscriber.
* @param ce {CustomEvent} The custom event that sent the notification.
*/
notify: function(args, ce) {
var c = this.context,
ret = true;
if (!c) {
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
if (Y.config && Y.config.throwFail) {
ret = this._notify(c, args, ce);
} else {
try {
ret = this._notify(c, args, ce);
} catch (e) {
Y.error(this + ' failed: ' + e.message, e);
}
}
return ret;
},
/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute.
* @param {Object} context optional 'this' keyword for the listener.
* @return {boolean} true if the supplied arguments match this
* subscriber's signature.
*/
contains: function(fn, context) {
if (context) {
return ((this.fn === fn) && this.context === context);
} else {
return (this.fn === fn);
}
},
valueOf : function() {
return this.id;
}
};
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param {CustomEvent} evt the custom event.
* @param {Subscriber} sub the subscriber.
*/
Y.EventHandle = function(evt, sub) {
/**
* The custom event
*
* @property evt
* @type CustomEvent
*/
this.evt = evt;
/**
* The subscriber object
*
* @property sub
* @type Subscriber
*/
this.sub = sub;
};
Y.EventHandle.prototype = {
batch: function(f, c) {
f.call(c || this, this);
if (Y.Lang.isArray(this.evt)) {
Y.Array.each(this.evt, function(h) {
h.batch.call(c || h, f);
});
}
},
/**
* Detaches this subscriber
* @method detach
* @return {Number} the number of detached listeners
*/
detach: function() {
var evt = this.evt, detached = 0, i;
if (evt) {
// Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event');
if (Y.Lang.isArray(evt)) {
for (i = 0; i < evt.length; i++) {
detached += evt[i].detach();
}
} else {
evt._delete(this.sub);
detached = 1;
}
}
return detached;
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('attach', 'detach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
return this.evt.monitor.apply(this.evt, arguments);
}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* EventTarget provides the implementation for any object to
* publish, subscribe and fire to custom events, and also
* alows other EventTargets to target the object with events
* sourced from the other object.
* EventTarget is designed to be used with Y.augment to wrap
* EventCustom in an interface that allows events to be listened to
* and fired by name. This makes it possible for implementing code to
* subscribe to an event that either has not been created yet, or will
* not be created at all.
* @class EventTarget
* @param opts a configuration object
* @config emitFacade {boolean} if true, all events will emit event
* facade payloads by default (default false)
* @config prefix {String} the prefix to apply to non-prefixed event names
*/
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
WILD_TYPE_RE = /(.*?)(:)(.*?)/,
_wildType = Y.cached(function(type) {
return type.replace(WILD_TYPE_RE, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = function(type, pre) {
if (!pre || !type || type.indexOf(PREFIX_DELIMITER) > -1) {
return type;
}
return pre + PREFIX_DELIMITER + type;
},
/**
* Returns an array with the detach key (if provided),
* and the prefixed event name from _getType
* Y.on('detachcategory| menu:click', fn)
* @method _parseType
* @private
*/
_parseType = Y.cached(function(type, pre) {
var t = type, detachcategory, after, i;
if (!L.isString(t)) {
return t;
}
i = t.indexOf(AFTER_PREFIX);
if (i > -1) {
after = true;
t = t.substr(AFTER_PREFIX.length);
}
i = t.indexOf(CATEGORY_DELIMITER);
if (i > -1) {
detachcategory = t.substr(0, (i));
t = t.substr(i+1);
if (t === '*') {
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
var etState = this._yuievt,
etConfig;
if (!etState) {
etState = this._yuievt = {
events: {}, // PERF: Not much point instantiating lazily. We're bound to have events
targets: null, // PERF: Instantiate lazily, if user actually adds target,
config: {
host: this,
context: this
},
chain: Y.config.chain
};
}
etConfig = etState.config;
if (opts) {
mixConfigs(etConfig, opts, true);
if (opts.chain !== undefined) {
etState.chain = opts.chain;
}
if (opts.prefix) {
etConfig.prefix = opts.prefix;
}
}
};
ET.prototype = {
constructor: ET,
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>on</code> except the
* listener is immediatelly detached when it is executed.
* @method once
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
once: function() {
var handle = this.on.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>after</code> except the
* listener is immediatelly detached when it is executed.
* @method onceAfter
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
onceAfter: function() {
var handle = this.after.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Takes the type parameter passed to 'on' and parses out the
* various pieces that could be included in the type. If the
* event type is passed without a prefix, it will be expanded
* to include the prefix one is supplied or the event target
* is configured with a default prefix.
* @method parseType
* @param {String} type the type
* @param {String} [pre] The prefix. Defaults to this._yuievt.config.prefix
* @since 3.3.0
* @return {Array} an array containing:
* * the detach category, if supplied,
* * the prefixed event type,
* * whether or not this is an after listener,
* * the supplied event type
*/
parseType: function(type, pre) {
return _parseType(type, pre || this._yuievt.config.prefix);
},
/**
* Subscribe a callback function to a custom event fired by this object or
* from an object that bubbles its events to this object.
*
* Callback functions for events published with `emitFacade = true` will
* receive an `EventFacade` as the first argument (typically named "e").
* These callbacks can then call `e.preventDefault()` to disable the
* behavior published to that event's `defaultFn`. See the `EventFacade`
* API for all available properties and methods. Subscribers to
* non-`emitFacade` events will receive the arguments passed to `fire()`
* after the event name.
*
* To subscribe to multiple events at once, pass an object as the first
* argument, where the key:value pairs correspond to the eventName:callback,
* or pass an array of event names as the first argument to subscribe to
* all listed events with the same callback.
*
* Returning `false` from a callback is supported as an alternative to
* calling `e.preventDefault(); e.stopPropagation();`. However, it is
* recommended to use the event methods whenever possible.
*
* @method on
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
on: function(type, fn, context) {
var yuievt = this._yuievt,
parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
if (L.isObject(type)) {
if (L.isFunction(type)) {
return Y.Do.before.apply(Y.Do, arguments);
}
f = fn;
c = context;
args = nativeSlice.call(arguments, 0);
ret = [];
if (L.isArray(type)) {
isArr = true;
}
after = type._after;
delete type._after;
Y.each(type, function(v, k) {
if (L.isObject(v)) {
f = v.fn || ((L.isFunction(v)) ? v : f);
c = v.context || c;
}
var nv = (after) ? AFTER_PREFIX : '';
args[0] = nv + ((isArr) ? v : k);
args[1] = f;
args[2] = c;
ret.push(this.on.apply(this, args));
}, this);
return (yuievt.chain) ? this : new Y.EventHandle(ret);
}
detachcategory = parts[0];
after = parts[2];
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {
args = nativeSlice.call(arguments, 0);
args.splice(2, 0, Node.getDOMNode(this));
// Y.log("Node detected, redirecting with these args: " + args);
return Y.on.apply(Y, args);
}
type = parts[1];
if (Y.instanceOf(this, YUI)) {
adapt = Y.Env.evt.plugins[type];
args = nativeSlice.call(arguments, 0);
args[0] = shorttype;
if (Node) {
n = args[2];
if (Y.instanceOf(n, Y.NodeList)) {
n = Y.NodeList.getDOMNodes(n);
} else if (Y.instanceOf(n, Node)) {
n = Node.getDOMNode(n);
}
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
if (domevent) {
args[2] = n;
}
}
// check for the existance of an event adaptor
if (adapt) {
Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event');
handle = adapt.on.apply(Y, args);
} else if ((!type) || domevent) {
handle = Y.Event._attach(args);
}
}
if (!handle) {
ce = yuievt.events[type] || this.publish(type);
handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);
// TODO: More robust regex, accounting for category
if (type.indexOf("*:") !== -1) {
this._hasSiblings = true;
}
}
if (detachcategory) {
store[detachcategory] = store[detachcategory] || {};
store[detachcategory][type] = store[detachcategory][type] || [];
store[detachcategory][type].push(handle);
}
return (yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated');
return this.on.apply(this, arguments);
},
/**
* Detach one or more listeners the from the specified event
* @method detach
* @param type {string|Object} Either the handle to the subscriber or the
* type of event. If the type
* is not specified, it will attempt to remove
* the listener from all hosted events.
* @param fn {Function} The subscribed function to unsubscribe, if not
* supplied, all subscribers will be removed.
* @param context {Object} The custom object passed to subscribe. This is
* optional, but if supplied will be used to
* disambiguate multiple listeners that are the same
* (e.g., you subscribe many object using a function
* that lives on the prototype)
* @return {EventTarget} the host
*/
detach: function(type, fn, context) {
var evts = this._yuievt.events,
i,
Node = Y.Node,
isNode = Node && (Y.instanceOf(this, Node));
// detachAll disabled on the Y instance.
if (!type && (this !== Y)) {
for (i in evts) {
if (evts.hasOwnProperty(i)) {
evts[i].detach(fn, context);
}
}
if (isNode) {
Y.Event.purgeElement(Node.getDOMNode(this));
}
return this;
}
var parts = _parseType(type, this._yuievt.config.prefix),
detachcategory = L.isArray(parts) ? parts[0] : null,
shorttype = (parts) ? parts[3] : null,
adapt, store = Y.Env.evt.handles, detachhost, cat, args,
ce,
keyDetacher = function(lcat, ltype, host) {
var handles = lcat[ltype], ce, i;
if (handles) {
for (i = handles.length - 1; i >= 0; --i) {
ce = handles[i].evt;
if (ce.host === host || ce.el === host) {
handles[i].detach();
}
}
}
};
if (detachcategory) {
cat = store[detachcategory];
type = parts[1];
detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;
if (cat) {
if (type) {
keyDetacher(cat, type, detachhost);
} else {
for (i in cat) {
if (cat.hasOwnProperty(i)) {
keyDetacher(cat, i, detachhost);
}
}
}
return this;
}
// If this is an event handle, use it to detach
} else if (L.isObject(type) && type.detach) {
type.detach();
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
args = nativeSlice.call(arguments, 0);
args[2] = Node.getDOMNode(this);
Y.detach.apply(Y, args);
return this;
}
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
if (Y.instanceOf(this, YUI)) {
args = nativeSlice.call(arguments, 0);
// use the adaptor specific detach code if
if (adapt && adapt.detach) {
adapt.detach.apply(Y, args);
return this;
// DOM event fork
} else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
args[0] = type;
Y.Event.detach.apply(Y.Event, args);
return this;
}
}
// ce = evts[type];
ce = evts[parts[1]];
if (ce) {
ce.detach(fn, context);
}
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated');
return this.detach.apply(this, arguments);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method detachAll
* @param type {String} The type, or name of the event
*/
detachAll: function(type) {
return this.detach(type);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method unsubscribeAll
* @param type {String} The type, or name of the event
* @deprecated use detachAll
*/
unsubscribeAll: function() {
Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated');
return this.detachAll.apply(this, arguments);
},
/**
* Creates a new custom event of the specified type. If a custom event
* by that name already exists, it will not be re-created. In either
* case the custom event is returned.
*
* @method publish
*
* @param type {String} the type, or name of the event
* @param opts {object} optional config params. Valid properties are:
*
* <ul>
* <li>
* 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)
* </li>
* <li>
* 'bubbles': whether or not this event bubbles (true)
* Events can only bubble if emitFacade is true.
* </li>
* <li>
* 'context': the default execution context for the listeners (this)
* </li>
* <li>
* 'defaultFn': the default function to execute when this event fires if preventDefault was not called
* </li>
* <li>
* 'emitFacade': whether or not this event emits a facade (false)
* </li>
* <li>
* 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'
* </li>
* <li>
* 'fireOnce': if an event is configured to fire once, new subscribers after
* the fire will be notified immediately.
* </li>
* <li>
* 'async': fireOnce event listeners will fire synchronously if the event has already
* fired unless async is true.
* </li>
* <li>
* 'preventable': whether or not preventDefault() has an effect (true)
* </li>
* <li>
* 'preventedFn': a function that is executed when preventDefault is called
* </li>
* <li>
* 'queuable': whether or not this event can be queued during bubbling (false)
* </li>
* <li>
* 'silent': if silent is true, debug messages are not provided for this event.
* </li>
* <li>
* 'stoppedFn': a function that is executed when stopPropagation is called
* </li>
*
* <li>
* 'monitored': specifies whether or not this event should send notifications about
* when the event has been attached, detached, or published.
* </li>
* <li>
* 'type': the event type (valid option if not provided as the first parameter to publish)
* </li>
* </ul>
*
* @return {CustomEvent} the custom event
*
*/
publish: function(type, opts) {
var ret,
etState = this._yuievt,
etConfig = etState.config,
pre = etConfig.prefix;
if (typeof type === "string") {
if (pre) {
type = _getType(type, pre);
}
ret = this._publish(type, etConfig, opts);
} else {
ret = {};
Y.each(type, function(v, k) {
if (pre) {
k = _getType(k, pre);
}
ret[k] = this._publish(k, etConfig, v || opts);
}, this);
}
return ret;
},
/**
* Returns the fully qualified type, given a short type string.
* That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix.
*
* NOTE: This method, unlike _getType, does no checking of the value passed in, and
* is designed to be used with the low level _publish() method, for critical path
* implementations which need to fast-track publish for performance reasons.
*
* @method _getFullType
* @private
* @param {String} type The short type to prefix
* @return {String} The prefixed type, if a prefix is set, otherwise the type passed in
*/
_getFullType : function(type) {
var pre = this._yuievt.config.prefix;
if (pre) {
return pre + PREFIX_DELIMITER + type;
} else {
return type;
}
},
/**
* The low level event publish implementation. It expects all the massaging to have been done
* outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast
* path publish, which can be used by critical code paths to improve performance.
*
* @method _publish
* @private
* @param {String} fullType The prefixed type of the event to publish.
* @param {Object} etOpts The EventTarget specific configuration to mix into the published event.
* @param {Object} ceOpts The publish specific configuration to mix into the published event.
* @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will
* be the default `CustomEvent` instance, and can be configured independently.
*/
_publish : function(fullType, etOpts, ceOpts) {
var ce,
etState = this._yuievt,
etConfig = etState.config,
host = etConfig.host,
context = etConfig.context,
events = etState.events;
ce = events[fullType];
// PERF: Hate to pull the check out of monitor, but trying to keep critical path tight.
if ((etConfig.monitored && !ce) || (ce && ce.monitored)) {
this._monitor('publish', fullType, {
args: arguments
});
}
if (!ce) {
// Publish event
ce = events[fullType] = new Y.CustomEvent(fullType, etOpts);
if (!etOpts) {
ce.host = host;
ce.context = context;
}
}
if (ceOpts) {
mixConfigs(ce, ceOpts, true);
}
return ce;
},
/**
* This is the entry point for the event monitoring system.
* You can monitor 'attach', 'detach', 'fire', and 'publish'.
* When configured, these events generate an event. click ->
* click_attach, click_detach, click_publish -- these can
* be subscribed to like other events to monitor the event
* system. Inividual published events can have monitoring
* turned on or off (publish can't be turned off before it
* it published) by setting the events 'monitor' config.
*
* @method _monitor
* @param what {String} 'attach', 'detach', 'fire', or 'publish'
* @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object.
* @param o {Object} Information about the event interaction, such as
* fire() args, subscription category, publish config
* @private
*/
_monitor: function(what, eventType, o) {
var monitorevt, ce, type;
if (eventType) {
if (typeof eventType === "string") {
type = eventType;
ce = this.getEvent(eventType, true);
} else {
ce = eventType;
type = eventType.type;
}
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
monitorevt = type + '_' + what;
o.monitored = what;
this.fire.call(this, monitorevt, o);
}
}
},
/**
* Fire a custom event by name. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters.
*
* 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.
*
* 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.
*
* @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 {Boolean} True if the whole lifecycle of the event went through,
* false if at any point the event propagation was halted.
*/
fire: function(type) {
var typeIncluded = (typeof type === "string"),
argCount = arguments.length,
t = type,
yuievt = this._yuievt,
etConfig = yuievt.config,
pre = etConfig.prefix,
ret,
ce,
ce2,
args;
if (typeIncluded && argCount <= 3) {
// PERF: Try to avoid slice/iteration for the common signatures
// Most common
if (argCount === 2) {
args = [arguments[1]]; // fire("foo", {})
} else if (argCount === 3) {
args = [arguments[1], arguments[2]]; // fire("foo", {}, opts)
} else {
args = []; // fire("foo")
}
} else {
args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0));
}
if (!typeIncluded) {
t = (type && type.type);
}
if (pre) {
t = _getType(t, pre);
}
ce = yuievt.events[t];
if (this._hasSiblings) {
ce2 = this.getSibling(t, ce);
if (ce2 && !ce) {
ce = this.publish(t);
}
}
// PERF: trying to avoid function call, since this is a critical path
if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
this._monitor('fire', (ce || t), {
args: args
});
}
// this event has not been published or subscribed to
if (!ce) {
if (yuievt.hasTargets) {
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
ret = true;
} else {
if (ce2) {
ce.sibling = ce2;
}
ret = ce._fire(args);
}
return (yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
var ce2;
// delegate to *:type events if there are subscribers
if (type.indexOf(PREFIX_DELIMITER) > -1) {
type = _wildType(type);
ce2 = this.getEvent(type, true);
if (ce2) {
ce2.applyConfig(ce);
ce2.bubbles = false;
ce2.broadcast = 0;
}
}
return ce2;
},
/**
* Returns the custom event of the provided type has been created, a
* falsy value otherwise
* @method getEvent
* @param type {String} the type, or name of the event
* @param prefixed {String} if true, the type is prefixed already
* @return {CustomEvent} the custom event or null
*/
getEvent: function(type, prefixed) {
var pre, e;
if (!prefixed) {
pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
}
e = this._yuievt.events;
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
*
* @method after
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
after: function(type, fn) {
var a = nativeSlice.call(arguments, 0);
switch (L.type(type)) {
case 'function':
return Y.Do.after.apply(Y.Do, arguments);
case 'array':
// YArray.each(a[0], function(v) {
// v = AFTER_PREFIX + v;
// });
// break;
case 'object':
a[0]._after = true;
break;
default:
a[0] = AFTER_PREFIX + type;
}
return this.on.apply(this, a);
},
/**
* Executes the callback before a DOM event, custom event
* or method. If the first argument is a function, it
* is assumed the target is a method. For DOM and custom
* events, this is an alias for Y.on.
*
* For DOM and custom events:
* type, callback, context, 0-n arguments
*
* For methods:
* callback, object (method host), methodName, context, 0-n arguments
*
* @method before
* @return detach handle
*/
before: function() {
return this.on.apply(this, arguments);
}
};
Y.EventTarget = ET;
// make Y an event target
Y.mix(Y, ET.prototype);
ET.call(Y, { bubbles: false });
YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();
/**
* Hosts YUI page level events. This is where events bubble to
* when the broadcast config is set to 2. This property is
* only available if the custom event module is loaded.
* @property Global
* @type EventTarget
* @for YUI
*/
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
/**
`Y.on()` can do many things:
<ul>
<li>Subscribe to custom events `publish`ed and `fire`d from Y</li>
<li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and
`fire`d from any object in the YUI instance sandbox</li>
<li>Subscribe to DOM events</li>
<li>Subscribe to the execution of a method on any object, effectively
treating that method as an event</li>
</ul>
For custom event subscriptions, pass the custom event name as the first argument
and callback as the second. The `this` object in the callback will be `Y` unless
an override is passed as the third argument.
Y.on('io:complete', function () {
Y.MyApp.updateStatus('Transaction complete');
});
To subscribe to DOM events, pass the name of a DOM event as the first argument
and a CSS selector string as the third argument after the callback function.
Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,
array, or simply omitted (the default is the `window` object).
Y.on('click', function (e) {
e.preventDefault();
// proceed with ajax form submission
var url = this.get('action');
...
}, '#my-form');
The `this` object in DOM event callbacks will be the `Node` targeted by the CSS
selector or other identifier.
`on()` subscribers for DOM events or custom events `publish`ed with a
`defaultFn` can prevent the default behavior with `e.preventDefault()` from the
event object passed as the first parameter to the subscription callback.
To subscribe to the execution of an object method, pass arguments corresponding to the call signature for
<a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>.
NOTE: The formal parameter list below is for events, not for function
injection. See `Y.Do.before` for that signature.
@method on
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@see Do.before
@for YUI
**/
/**
Listen for an event one time. Equivalent to `on()`, except that
the listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see on
@method once
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Listen for an event one time. Equivalent to `once()`, except, like `after()`,
the subscription callback executes after all `on()` subscribers and the event's
`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase
subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`
subscribers will execute.
The listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see once
@method onceAfter
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Like `on()`, this method creates a subscription to a custom event or to the
execution of a method on an object.
For events, `after()` subscribers are executed after the event's
`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
NOTE: The subscription signature shown is for events, not for function
injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a>
for that signature.
@see on
@see Do.after
@method after
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [args*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
}, '3.15.0', {"requires": ["oop"]});
|
grunt/tasks/release.js | evilemon/react | 'use strict';
var grunt = require('grunt');
var BOWER_PATH = '../react-bower/';
var BOWER_GLOB = [BOWER_PATH + '*.{js}'];
var BOWER_FILES = [
'react.js', 'react.min.js', 'JSXTransformer.js',
'react-with-addons.js', 'react-with-addons.min.js',
];
var GH_PAGES_PATH = '../react-gh-pages/';
var GH_PAGES_GLOB = [GH_PAGES_PATH + '*'];
var EXAMPLES_PATH = 'examples/';
var EXAMPLES_GLOB = [EXAMPLES_PATH + '**/*.*'];
var STARTER_PATH = 'starter/';
var STARTER_GLOB = [STARTER_PATH + '/**/*.*'];
var STARTER_BUILD_PATH = 'build/starter/';
var JS_PATH = 'build/';
var JS_GLOB = [JS_PATH + '/*.js'];
var VERSION;
var VERSION_STRING;
function _gitCommitAndTag(cwd, commitMsg, tag, cb) {
// `git add *` to make sure we catch untracked files
// `git add -u` to make sure we remove deleted files
// `git commit -m {commitMsg}`
// `git tag -a {tag}`
var opts = {cwd: cwd};
var gitAddAll = {
cmd: 'git',
args: ['add', '*'],
opts: opts,
};
var gitAddDel = {
cmd: 'git',
args: ['add', '-u'],
opts: opts,
};
var gitCommit = {
cmd: 'git',
args: ['commit', '-m', commitMsg],
opts: opts,
};
var gitTag = {
cmd: 'git',
args: ['tag', tag],
opts: opts,
};
grunt.util.spawn(gitAddAll, function() {
grunt.util.spawn(gitAddDel, function() {
grunt.util.spawn(gitCommit, function() {
if (tag) {
grunt.util.spawn(gitTag, cb);
} else {
cb();
}
});
});
});
}
function setup() {
if (!grunt.file.exists(BOWER_PATH)) {
grunt.log.error('Make sure you have the react-bower repository checked ' +
'out at ../react-bower');
return false;
}
if (!grunt.file.exists(GH_PAGES_PATH)) {
grunt.log.error('Make sure you have the react gh-pages branch checked ' +
'out at ../react-gh-pages.');
return false;
}
VERSION = grunt.config.data.pkg.version;
VERSION_STRING = 'v' + VERSION;
}
function bower() {
var done = this.async();
// clean out the bower folder in case we're removing files
var files = grunt.file.expand(BOWER_GLOB);
files.forEach(function(file) {
grunt.file.delete(file, {force: true});
});
// Now copy over build files
BOWER_FILES.forEach(function(file) {
grunt.file.copy('build/' + file, BOWER_PATH + file);
});
// Commit and tag the repo
_gitCommitAndTag(BOWER_PATH, VERSION_STRING, VERSION_STRING, done);
}
function docs() {
var done = this.async();
grunt.file.copy('build/react-' + VERSION + '.zip', 'docs/downloads/react-' + VERSION + '.zip');
grunt.file.copy('build/react.js', 'docs/js/react.js');
grunt.file.copy('build/JSXTransformer.js', 'docs/js/JSXTransformer.js');
var files = grunt.file.expand(GH_PAGES_GLOB);
files.forEach(function(file) {
grunt.file.delete(file, {force: true});
});
// Build the docs with `rake release`, which will compile the CSS & JS, then
// build jekyll into GH_PAGES_PATH
var rakeOpts = {
cmd: 'rake',
args: ['release'],
opts: {cwd: 'docs'},
};
grunt.util.spawn(rakeOpts, function() {
// Commit the repo. We don't really care about tagging this.
_gitCommitAndTag(GH_PAGES_PATH, VERSION_STRING, null, done);
});
}
function msg() {
// Just output a friendly reminder message for the rest of the process
grunt.log.subhead('Release *almost* complete...');
var steps = [
'Still todo:',
'* put files on CDN',
'* push changes to git repositories',
'* publish npm module (`npm publish .`)',
'* announce it on FB/Twitter/mailing list',
];
steps.forEach(function(ln) {
grunt.log.writeln(ln);
});
}
function starter() {
// Copy over examples/ to build/starter/examples/
// and starter/ to build/starter/
grunt.file.expand(EXAMPLES_GLOB).forEach(function(file) {
grunt.file.copy(
file,
STARTER_BUILD_PATH + file
);
});
grunt.file.expand(STARTER_GLOB).forEach(function(file) {
grunt.file.copy(
file,
'build/' + file
);
});
grunt.file.expand(JS_GLOB).forEach(function(file) {
grunt.file.copy(
file,
STARTER_BUILD_PATH + file
);
});
}
module.exports = {
setup: setup,
bower: bower,
docs: docs,
msg: msg,
starter: starter,
};
|
node_modules/babel-core/lib/transformation/file/index.js | yomolify/cs-webserver | "use strict";
exports.__esModule = true;
// istanbul ignore next
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; }; })();
// istanbul ignore next
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; } }
// istanbul ignore next
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// istanbul ignore next
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _convertSourceMap = require("convert-source-map");
var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap);
var _modules = require("../modules");
var _modules2 = _interopRequireDefault(_modules);
var _optionsOptionManager = require("./options/option-manager");
var _optionsOptionManager2 = _interopRequireDefault(_optionsOptionManager);
var _pluginManager = require("./plugin-manager");
var _pluginManager2 = _interopRequireDefault(_pluginManager);
var _shebangRegex = require("shebang-regex");
var _shebangRegex2 = _interopRequireDefault(_shebangRegex);
var _traversalPath = require("../../traversal/path");
var _traversalPath2 = _interopRequireDefault(_traversalPath);
var _lodashLangIsFunction = require("lodash/lang/isFunction");
var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction);
var _sourceMap = require("source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _generation = require("../../generation");
var _generation2 = _interopRequireDefault(_generation);
var _helpersCodeFrame = require("../../helpers/code-frame");
var _helpersCodeFrame2 = _interopRequireDefault(_helpersCodeFrame);
var _lodashObjectDefaults = require("lodash/object/defaults");
var _lodashObjectDefaults2 = _interopRequireDefault(_lodashObjectDefaults);
var _lodashCollectionIncludes = require("lodash/collection/includes");
var _lodashCollectionIncludes2 = _interopRequireDefault(_lodashCollectionIncludes);
var _traversal = require("../../traversal");
var _traversal2 = _interopRequireDefault(_traversal);
var _tryResolve = require("try-resolve");
var _tryResolve2 = _interopRequireDefault(_tryResolve);
var _logger = require("./logger");
var _logger2 = _interopRequireDefault(_logger);
var _plugin = require("../plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _helpersParse = require("../../helpers/parse");
var _helpersParse2 = _interopRequireDefault(_helpersParse);
var _traversalHub = require("../../traversal/hub");
var _traversalHub2 = _interopRequireDefault(_traversalHub);
var _util = require("../../util");
var util = _interopRequireWildcard(_util);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
/**
* [Please add a description.]
*/
var File = (function () {
function File(opts, pipeline) {
if (opts === undefined) opts = {};
_classCallCheck(this, File);
this.transformerDependencies = {};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.declarations = {};
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.ast = {};
this.metadata = {
modules: {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
};
this.hub = new _traversalHub2["default"](this);
this.pipeline = pipeline;
this.log = new _logger2["default"](this, opts.filename || "unknown");
this.opts = this.initOptions(opts);
this.buildTransformers();
}
/**
* [Please add a description.]
*/
File.prototype.initOptions = function initOptions(opts) {
opts = new _optionsOptionManager2["default"](this.log, this.pipeline).init(opts);
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = _path2["default"].basename(opts.filename, _path2["default"].extname(opts.filename));
opts.ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
_lodashObjectDefaults2["default"](opts, {
moduleRoot: opts.sourceRoot
});
_lodashObjectDefaults2["default"](opts, {
sourceRoot: opts.moduleRoot
});
_lodashObjectDefaults2["default"](opts, {
filenameRelative: opts.filename
});
_lodashObjectDefaults2["default"](opts, {
sourceFileName: opts.filenameRelative,
sourceMapTarget: opts.filenameRelative
});
//
if (opts.externalHelpers) {
this.set("helpersNamespace", t.identifier("babelHelpers"));
}
return opts;
};
/**
* [Please add a description.]
*/
File.prototype.isLoose = function isLoose(key) {
return _lodashCollectionIncludes2["default"](this.opts.loose, key);
};
/**
* [Please add a description.]
*/
File.prototype.buildTransformers = function buildTransformers() {
var file = this;
var transformers = this.transformers = {};
var secondaryStack = [];
var stack = [];
// build internal transformers
for (var key in this.pipeline.transformers) {
var transformer = this.pipeline.transformers[key];
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canTransform()) {
stack.push(pass);
if (transformer.metadata.secondPass) {
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
}
// init plugins!
var beforePlugins = [];
var afterPlugins = [];
var pluginManager = new _pluginManager2["default"]({
file: this,
transformers: this.transformers,
before: beforePlugins,
after: afterPlugins
});
for (var i = 0; i < file.opts.plugins.length; i++) {
pluginManager.add(file.opts.plugins[i]);
}
stack = beforePlugins.concat(stack, afterPlugins);
// build transformer stack
this.uncollapsedTransformerStack = stack = stack.concat(secondaryStack);
// build dependency graph
var _arr = stack;
for (var _i = 0; _i < _arr.length; _i++) {
var pass = _arr[_i];var _arr2 = pass.plugin.dependencies;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var dep = _arr2[_i2];
this.transformerDependencies[dep] = pass.key;
}
}
// collapse stack categories
this.transformerStack = this.collapseStack(stack);
};
/**
* [Please add a description.]
*/
File.prototype.collapseStack = function collapseStack(_stack) {
var stack = [];
var ignore = [];
var _arr3 = _stack;
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var pass = _arr3[_i3];
// been merged
if (ignore.indexOf(pass) >= 0) continue;
var group = pass.plugin.metadata.group;
// can't merge
if (!pass.canTransform() || !group) {
stack.push(pass);
continue;
}
var mergeStack = [];
var _arr4 = _stack;
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var _pass = _arr4[_i4];
if (_pass.plugin.metadata.group === group) {
mergeStack.push(_pass);
ignore.push(_pass);
}
}
var visitors = [];
var _arr5 = mergeStack;
for (var _i5 = 0; _i5 < _arr5.length; _i5++) {
var _pass2 = _arr5[_i5];
visitors.push(_pass2.plugin.visitor);
}
var visitor = _traversal2["default"].visitors.merge(visitors);
var mergePlugin = new _plugin2["default"](group, { visitor: visitor });
stack.push(mergePlugin.buildPass(this));
}
return stack;
};
/**
* [Please add a description.]
*/
File.prototype.set = function set(key, val) {
return this.data[key] = val;
};
/**
* [Please add a description.]
*/
File.prototype.setDynamic = function setDynamic(key, fn) {
this.dynamicData[key] = fn;
};
/**
* [Please add a description.]
*/
File.prototype.get = function get(key) {
var data = this.data[key];
if (data) {
return data;
} else {
var dynamic = this.dynamicData[key];
if (dynamic) {
return this.set(key, dynamic());
}
}
};
/**
* [Please add a description.]
*/
File.prototype.resolveModuleSource = function resolveModuleSource(source) {
var resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
};
/**
* [Please add a description.]
*/
File.prototype.addImport = function addImport(source, name, type) {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
source = this.resolveModuleSource(source);
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);
var specifiers = [t.importDefaultSpecifier(id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
if (type) {
var modules = this.dynamicImportTypes[type] = this.dynamicImportTypes[type] || [];
modules.push(declar);
}
if (this.transformers["es6.modules"].canTransform()) {
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports, this.scope);
this.moduleFormatter.hasLocalImports = true;
} else {
this.dynamicImports.push(declar);
}
}
return id;
};
/**
* [Please add a description.]
*/
File.prototype.attachAuxiliaryComment = function attachAuxiliaryComment(node) {
var beforeComment = this.opts.auxiliaryCommentBefore;
if (beforeComment) {
node.leadingComments = node.leadingComments || [];
node.leadingComments.push({
type: "CommentLine",
value: " " + beforeComment
});
}
var afterComment = this.opts.auxiliaryCommentAfter;
if (afterComment) {
node.trailingComments = node.trailingComments || [];
node.trailingComments.push({
type: "CommentLine",
value: " " + afterComment
});
}
return node;
};
/**
* [Please add a description.]
*/
File.prototype.addHelper = function addHelper(name) {
var isSolo = _lodashCollectionIncludes2["default"](File.soloHelpers, name);
if (!isSolo && !_lodashCollectionIncludes2["default"](File.helpers, name)) {
throw new ReferenceError("Unknown helper " + name);
}
var declar = this.declarations[name];
if (declar) return declar;
this.usedHelpers[name] = true;
if (!isSolo) {
var generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) {
return generator(name);
} else if (runtime) {
var id = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, id);
}
}
var ref = util.template("helper-" + name);
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.attachAuxiliaryComment(ref);
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
this.scope.push({
id: uid,
init: ref,
unique: true
});
}
return uid;
};
File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) {
// Generate a unique name based on the string literals so we dedupe
// identical strings used in the program.
var stringIds = raw.elements.map(function (string) {
return string.value;
});
var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(",");
var declar = this.declarations[name];
if (declar) return declar;
var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
var helperId = this.addHelper(helperName);
var init = t.callExpression(helperId, [strings, raw]);
init._compact = true;
this.scope.push({
id: uid,
init: init,
_blockHoist: 1.9 // This ensures that we don't fail if not using function expression helpers
});
return uid;
};
/**
* [Please add a description.]
*/
File.prototype.errorWithNode = function errorWithNode(node, msg) {
var Error = arguments.length <= 2 || arguments[2] === undefined ? SyntaxError : arguments[2];
var err;
var loc = node && (node.loc || node._loc);
if (loc) {
err = new Error("Line " + loc.start.line + ": " + msg);
err.loc = loc.start;
} else {
// todo: find errors with nodes inside to at least point to something
err = new Error("There's been an error on a dynamic node. This is almost certainly an internal error. Please report it.");
}
return err;
};
/**
* [Please add a description.]
*/
File.prototype.mergeSourceMap = function mergeSourceMap(map) {
var opts = this.opts;
var inputMap = opts.inputSourceMap;
if (inputMap) {
map.sources[0] = inputMap.file;
var inputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(inputMap);
var outputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(map);
var outputMapGenerator = _sourceMap2["default"].SourceMapGenerator.fromSourceMap(outputMapConsumer);
outputMapGenerator.applySourceMap(inputMapConsumer);
var mergedMap = outputMapGenerator.toJSON();
mergedMap.sources = inputMap.sources;
mergedMap.file = inputMap.file;
return mergedMap;
}
return map;
};
/**
* [Please add a description.]
*/
File.prototype.getModuleFormatter = function getModuleFormatter(type) {
if (_lodashLangIsFunction2["default"](type) || !_modules2["default"][type]) {
this.log.deprecate("Custom module formatters are deprecated and will be removed in the next major. Please use Babel plugins instead.");
}
var ModuleFormatter = _lodashLangIsFunction2["default"](type) ? type : _modules2["default"][type];
if (!ModuleFormatter) {
var loc = _tryResolve2["default"].relative(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type));
}
return new ModuleFormatter(this);
};
/**
* [Please add a description.]
*/
File.prototype.parse = function parse(code) {
var opts = this.opts;
//
var parseOpts = {
highlightCode: opts.highlightCode,
nonStandard: opts.nonStandard,
sourceType: opts.sourceType,
filename: opts.filename,
plugins: {}
};
var features = parseOpts.features = {};
for (var key in this.transformers) {
var transformer = this.transformers[key];
features[key] = transformer.canTransform();
}
parseOpts.looseModules = this.isLoose("es6.modules");
parseOpts.strictMode = features.strict;
this.log.debug("Parse start");
var ast = _helpersParse2["default"](code, parseOpts);
this.log.debug("Parse stop");
return ast;
};
/**
* [Please add a description.]
*/
File.prototype._addAst = function _addAst(ast) {
this.path = _traversalPath2["default"].get({
hub: this.hub,
parentPath: null,
parent: ast,
container: ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
this.ast = ast;
};
/**
* [Please add a description.]
*/
File.prototype.addAst = function addAst(ast) {
this.log.debug("Start set AST");
this._addAst(ast);
this.log.debug("End set AST");
this.log.debug("Start module formatter init");
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
modFormatter.init();
}
this.log.debug("End module formatter init");
};
/**
* [Please add a description.]
*/
File.prototype.transform = function transform() {
this.call("pre");
var _arr6 = this.transformerStack;
for (var _i6 = 0; _i6 < _arr6.length; _i6++) {
var pass = _arr6[_i6];
pass.transform();
}
this.call("post");
return this.generate();
};
/**
* [Please add a description.]
*/
File.prototype.wrap = function wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return this.makeResult({ code: code, ignored: true });
} else {
return callback();
}
} catch (err) {
if (err._babel) {
throw err;
} else {
err._babel = true;
}
var message = err.message = this.opts.filename + ": " + err.message;
var loc = err.loc;
if (loc) {
err.codeFrame = _helpersCodeFrame2["default"](code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
}
if (process.browser) {
// chrome has it's own pretty stringifier which doesn't use the stack property
// https://github.com/babel/babel/issues/2175
err.message = message;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
try {
err.stack = newStack;
} catch (e) {
// `err.stack` may be a readonly property in some environments
}
}
throw err;
}
};
/**
* [Please add a description.]
*/
File.prototype.addCode = function addCode(code) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
};
/**
* [Please add a description.]
*/
File.prototype.parseCode = function parseCode() {
this.parseShebang();
var ast = this.parse(this.code);
this.addAst(ast);
};
/**
* [Please add a description.]
*/
File.prototype.shouldIgnore = function shouldIgnore() {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
};
/**
* [Please add a description.]
*/
File.prototype.call = function call(key) {
var _arr7 = this.uncollapsedTransformerStack;
for (var _i7 = 0; _i7 < _arr7.length; _i7++) {
var pass = _arr7[_i7];
var fn = pass.plugin[key];
if (fn) fn(this);
}
};
/**
* [Please add a description.]
*/
File.prototype.parseInputSourceMap = function parseInputSourceMap(code) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = _convertSourceMap2["default"].fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = _convertSourceMap2["default"].removeComments(code);
}
}
return code;
};
/**
* [Please add a description.]
*/
File.prototype.parseShebang = function parseShebang() {
var shebangMatch = _shebangRegex2["default"].exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(_shebangRegex2["default"], "");
}
};
/**
* [Please add a description.]
*/
File.prototype.makeResult = function makeResult(_ref) {
var code = _ref.code;
var _ref$map = _ref.map;
var map = _ref$map === undefined ? null : _ref$map;
var ast = _ref.ast;
var ignored = _ref.ignored;
var result = {
metadata: null,
ignored: !!ignored,
code: null,
ast: null,
map: map
};
if (this.opts.code) {
result.code = code;
}
if (this.opts.ast) {
result.ast = ast;
}
if (this.opts.metadata) {
result.metadata = this.metadata;
result.metadata.usedHelpers = Object.keys(this.usedHelpers);
}
return result;
};
/**
* [Please add a description.]
*/
File.prototype.generate = function generate() {
var opts = this.opts;
var ast = this.ast;
var result = { ast: ast };
if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start");
var _result = _generation2["default"](ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
if (this.shebang) {
// add back shebang
result.code = this.shebang + "\n" + result.code;
}
if (result.map) {
result.map = this.mergeSourceMap(result.map);
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
result.code += "\n" + _convertSourceMap2["default"].fromObject(result.map).toComment();
}
if (opts.sourceMaps === "inline") {
result.map = null;
}
return this.makeResult(result);
};
_createClass(File, null, [{
key: "helpers",
/**
* [Please add a description.]
*/
value: ["inherits", "defaults", "create-class", "create-decorated-class", "create-decorated-object", "define-decorated-property-descriptor", "tagged-template-literal", "tagged-template-literal-loose", "to-array", "to-consumable-array", "sliced-to-array", "sliced-to-array-loose", "object-without-properties", "has-own", "slice", "bind", "define-property", "async-to-generator", "interop-export-wildcard", "interop-require-wildcard", "interop-require-default", "typeof", "extends", "get", "set", "new-arrow-check", "class-call-check", "object-destructuring-empty", "temporal-undefined", "temporal-assert-defined", "self-global", "typeof-react-element", "default-props", "instanceof",
// legacy
"interop-require"],
/**
* [Please add a description.]
*/
enumerable: true
}, {
key: "soloHelpers",
value: [],
enumerable: true
}]);
return File;
})();
exports["default"] = File;
module.exports = exports["default"]; |
src/components/Toolbar.js | dominic-blain/viper-visualizer | import React from 'react';
import {connect} from 'react-redux';
import ActionCreators from '../actions/ActionCreators';
import ToolbarTabButton from './ToolbarTabButton';
import ToolbarTabContent from './ToolbarTabContent';
import ToolbarTabList from './ToolbarTabList';
import ToolbarListButton from './ToolbarListButton';
import ToolbarGroup from './ToolbarGroup';
import ToolbarInput from './ToolbarInput';
import ToolbarModule from './ToolbarModule';
import TabTokens from './TabTokens';
import TabTypography from './TabTypography';
import TabModules from './TabModules';
import ButtonSave from './ButtonSave';
class Toolbar extends React.Component {
render() {
const activeTab = {
tokens: this.props.activeTab == "tokens",
typography: this.props.activeTab == "typography",
modules: this.props.activeTab == "modules"
};
const activeTabItem = this.props.activeTabItem;
const onTabButtonClick = this.props.onTabButtonClick;
const buttonSaveState = this.props.buttonSaveState;
const onButtonSaveClick = this.props.onButtonSaveClick;
return (
<aside className="toolbar-zone">
<div className="toolbar-ctn">
<nav className="toolbar-tabs">
<div className="toolbar-scroll">
<div className="toolbar-tabs-wrapper">
<ToolbarTabButton
name="tokens"
label="Tokens"
isActive={activeTab.tokens}
onClick={onTabButtonClick}
/>
<ToolbarTabButton
name="typography"
label="Typography"
isActive={activeTab.typography}
onClick={onTabButtonClick}
/>
<ToolbarTabButton
name="modules"
label="Modules"
isActive={activeTab.modules}
onClick={onTabButtonClick}
/>
</div>
</div>
</nav>
<main className="toolbar-content">
<TabTokens isActive={activeTab.tokens}/>
<TabTypography isActive={activeTab.typography}/>
<TabModules isActive={activeTab.modules}/>
</main>
<footer className="toolbar-buttons">
<ButtonSave
saveState={buttonSaveState}
onClick={onButtonSaveClick}
/>
</footer>
</div>
</aside>
);
}
}
const mapDispatchToProps = (dispatch) => ({
onTabButtonClick: (tabName) => dispatch(ActionCreators.changeTab(tabName)),
onButtonSaveClick: () => dispatch(ActionCreators.saveProject())
});
const mapStateToProps = (state) => ({
activeTab: state.activeTab,
activeTabItem: state.activeTabItem,
tokensGroups: state.tokensGroups,
tokens: state.tokens,
modulesSchema: state.modulesSchema,
modules: state.modules,
options: state.options,
fontRecipes: state.fontRecipes,
fonts: state.fonts,
buttonSaveState: state.ui.buttonSaveState
});
export default connect(mapStateToProps, mapDispatchToProps)(Toolbar);
|
app/javascript/mastodon/features/ui/components/video_modal.js | yukimochi/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>
);
}
}
|
ajax/libs/rxjs/4.0.4/rx.lite.extras.js | wil93/cdnjs | // Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
;(function (factory) {
var objectTypes = {
'function': true,
'object': true
};
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['./rx.lite'], function (Rx, exports) {
return factory(root, exports, Rx);
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require('rx-lite'));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function (root, exp, Rx, undefined) {
// References
var Observable = Rx.Observable,
observableProto = Observable.prototype,
observableNever = Observable.never,
observableThrow = Observable['throw'],
AnonymousObservable = Rx.AnonymousObservable,
ObservableBase = Rx.ObservableBase,
AnonymousObserver = Rx.AnonymousObserver,
notificationCreateOnNext = Rx.Notification.createOnNext,
notificationCreateOnError = Rx.Notification.createOnError,
notificationCreateOnCompleted = Rx.Notification.createOnCompleted,
Observer = Rx.Observer,
observerCreate = Observer.create,
AbstractObserver = Rx.internals.AbstractObserver,
Subject = Rx.Subject,
internals = Rx.internals,
helpers = Rx.helpers,
ScheduledObserver = internals.ScheduledObserver,
SerialDisposable = Rx.SerialDisposable,
SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
CompositeDisposable = Rx.CompositeDisposable,
BinaryDisposable = Rx.BinaryDisposable,
RefCountDisposable = Rx.RefCountDisposable,
disposableEmpty = Rx.Disposable.empty,
immediateScheduler = Rx.Scheduler.immediate,
defaultKeySerializer = helpers.defaultKeySerializer,
addRef = Rx.internals.addRef,
identity = helpers.identity,
isPromise = helpers.isPromise,
isFunction = helpers.isFunction,
inherits = internals.inherits,
bindCallback = internals.bindCallback,
noop = helpers.noop,
isScheduler = Rx.Scheduler.isScheduler,
observableFromPromise = Observable.fromPromise,
ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError;
var errorObj = {e: {}};
function tryCatcherGen(tryCatchTarget) {
return function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
};
}
var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
return tryCatcherGen(fn);
};
function thrower(e) {
throw e;
}
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.schedule(this, scheduleItem);
};
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Creates an observer from a notification callback.
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
var handlerFunc = bindCallback(handler, thisArg, 1);
return new AnonymousObserver(function (x) {
return handlerFunc(notificationCreateOnNext(x));
}, function (e) {
return handlerFunc(notificationCreateOnError(e));
}, function () {
return handlerFunc(notificationCreateOnCompleted());
});
};
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
var source = this;
return new AnonymousObserver(
function (x) { source.onNext(x); },
function (e) { source.onError(e); },
function () { source.onCompleted(); }
);
};
var ObserveOnObservable = (function (__super__) {
inherits(ObserveOnObservable, __super__);
function ObserveOnObservable(source, s) {
this.source = source;
this._s = s;
__super__.call(this);
}
ObserveOnObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new ObserveOnObserver(this._s, o));
};
return ObserveOnObservable;
}(ObservableBase));
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
return new ObserveOnObservable(this, scheduler);
};
var SubscribeOnObservable = (function (__super__) {
inherits(SubscribeOnObservable, __super__);
function SubscribeOnObservable(source, s) {
this.source = source;
this._s = s;
__super__.call(this);
}
function scheduleMethod(scheduler, state) {
var source = state[0], d = state[1], o = state[2];
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o)));
}
SubscribeOnObservable.prototype.subscribeCore = function (o) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod));
return d;
};
return SubscribeOnObservable;
}(ObservableBase));
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
return new SubscribeOnObservable(this, scheduler);
};
var GenerateObservable = (function (__super__) {
inherits(GenerateObservable, __super__);
function GenerateObservable(state, cndFn, itrFn, resFn, s) {
this._state = state;
this._cndFn = cndFn;
this._itrFn = itrFn;
this._resFn = resFn;
this._s = s;
this._first = true;
__super__.call(this);
}
function scheduleRecursive(self, recurse) {
if (self._first) {
self._first = false;
} else {
self._state = tryCatch(self._itrFn)(self._state);
if (self._state === errorObj) { return self._o.onError(self._state.e); }
}
var hasResult = tryCatch(self._cndFn)(self._state);
if (hasResult === errorObj) { return self._o.onError(hasResult.e); }
if (hasResult) {
var result = tryCatch(self._resFn)(self._state);
if (result === errorObj) { return self._o.onError(result.e); }
self._o.onNext(result);
recurse(self);
} else {
self._o.onCompleted();
}
}
GenerateObservable.prototype.subscribeCore = function (o) {
this._o = o;
return this._s.scheduleRecursive(this, scheduleRecursive);
};
return GenerateObservable;
}(ObservableBase));
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new GenerateObservable(initialState, condition, iterate, resultSelector, scheduler);
};
var UsingObservable = (function (__super__) {
inherits(UsingObservable, __super__);
function UsingObservable(resFn, obsFn) {
this._resFn = resFn;
this._obsFn = obsFn;
__super__.call(this);
}
UsingObservable.prototype.subscribeCore = function (o) {
var disposable = disposableEmpty;
var resource = tryCatch(this._resFn)();
if (resource === errorObj) {
return new BinaryDisposable(observableThrow(resource.e).subscribe(o), disposable);
}
resource && (disposable = resource);
var source = tryCatch(this._obsFn)(resource);
if (source === errorObj) {
return new BinaryDisposable(observableThrow(source.e).subscribe(o), disposable);
}
return new BinaryDisposable(source.subscribe(o), disposable);
};
return UsingObservable;
}(ObservableBase));
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new UsingObservable(resourceFactory, observableFactory);
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
var leftSubscribe = observerCreate(
function (left) {
choiceL();
choice === leftChoice && observer.onNext(left);
},
function (e) {
choiceL();
choice === leftChoice && observer.onError(e);
},
function () {
choiceL();
choice === leftChoice && observer.onCompleted();
}
);
var rightSubscribe = observerCreate(
function (right) {
choiceR();
choice === rightChoice && observer.onNext(right);
},
function (e) {
choiceR();
choice === rightChoice && observer.onError(e);
},
function () {
choiceR();
choice === rightChoice && observer.onCompleted();
}
);
leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));
return new BinaryDisposable(leftSubscription, rightSubscription);
});
};
function amb(p, c) { return p.amb(c); }
/**
* Propagates the observable sequence or Promise that reacts first.
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items;
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
var len = arguments.length;
items = new Array(items);
for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
}
for (var i = 0, len = items.length; i < len; i++) {
acc = amb(acc, items[i]);
}
return acc;
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(null, function (_, self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new BinaryDisposable(subscription, cancelable);
});
};
function toArray(x) { return x.toArray(); }
function notEmpty(x) { return x.length > 0; }
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
typeof skip !== 'number' && (skip = count);
return this.windowWithCount(count, skip)
.flatMap(toArray)
.filter(notEmpty);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
var TakeLastBufferObserver = (function (__super__) {
inherits(TakeLastBufferObserver, __super__);
function TakeLastBufferObserver(o, c) {
this._o = o;
this._c = c;
this._q = [];
__super__.call(this);
}
TakeLastBufferObserver.prototype.next = function (x) {
this._q.push(x);
this._q.length > this._c && this._q.shift();
};
TakeLastBufferObserver.prototype.error = function (e) {
this._o.onError(e);
};
TakeLastBufferObserver.prototype.completed = function () {
this._o.onNext(this._q);
this._o.onCompleted();
};
return TakeLastBufferObserver;
}(AbstractObserver));
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(new TakeLastBufferObserver(o, count));
}, source);
};
var DefaultIfEmptyObserver = (function (__super__) {
inherits(DefaultIfEmptyObserver, __super__);
function DefaultIfEmptyObserver(o, d) {
this._o = o;
this._d = d;
this._f = false;
__super__.call(this);
}
DefaultIfEmptyObserver.prototype.next = function (x) {
this._f = true;
this._o.onNext(x);
};
DefaultIfEmptyObserver.prototype.error = function (e) {
this._o.onError(e);
};
DefaultIfEmptyObserver.prototype.completed = function () {
!this._f && this._o.onNext(this._d);
this._o.onCompleted();
};
return DefaultIfEmptyObserver;
}(AbstractObserver));
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (o) {
return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue));
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
var DistinctObservable = (function (__super__) {
inherits(DistinctObservable, __super__);
function DistinctObservable(source, keyFn, cmpFn) {
this.source = source;
this._keyFn = keyFn;
this._cmpFn = cmpFn;
__super__.call(this);
}
DistinctObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn));
};
return DistinctObservable;
}(ObservableBase));
var DistinctObserver = (function (__super__) {
inherits(DistinctObserver, __super__);
function DistinctObserver(o, keyFn, cmpFn) {
this._o = o;
this._keyFn = keyFn;
this._h = new HashSet(cmpFn);
__super__.call(this);
}
DistinctObserver.prototype.next = function (x) {
var key = x;
if (isFunction(this._keyFn)) {
key = tryCatch(this._keyFn)(x);
if (key === errorObj) { return this._o.onError(key.e); }
}
this._h.push(key) && this._o.onNext(x);
};
DistinctObserver.prototype.error = function (e) { this._o.onError(e); };
DistinctObserver.prototype.completed = function () { this._o.onCompleted(); };
return DistinctObserver;
}(AbstractObserver));
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
comparer || (comparer = defaultComparer);
return new DistinctObservable(this, keySelector, comparer);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
* can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
*/
observableProto.singleInstance = function() {
var source = this, hasObservable = false, observable;
function getObservable() {
if (!hasObservable) {
hasObservable = true;
observable = source.finally(function() { hasObservable = false; }).publish().refCount();
}
return observable;
}
return new AnonymousObservable(function(o) {
return getObservable().subscribe(o);
});
};
return Rx;
}));
|
packages/material-ui-icons/src/Brightness6Sharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18V6c3.31 0 6 2.69 6 6s-2.69 6-6 6z" /></g></React.Fragment>
, 'Brightness6Sharp');
|
src/components/List.js | nayed/hanews | import React from 'react'
import Button from './Button'
import '../styles/List.sass'
const PATH_HN = 'https://news.ycombinator.com'
const PATH_POST = '/item?id='
const PATH_USER = '/user?id='
const List = ({ list, onDismiss }) => {
return (
<div>
{ list.map(item =>
<div key={item.objectID}>
<div className="row">
<div className="col-sm-3 col-md-4"></div>
<div className="item col-sm-6 col-md-4">
<div className="title">
<a href={item.url} data-toggle="tooltip" title={item.title}>
{displayItem(item)}
</a>
</div>
<span className="info">by <a href={`${PATH_HN}${PATH_USER}${item.author}`}>{item.author}</a></span>|
<span className="info"><a href={`${PATH_HN}${PATH_POST}${item.objectID}`}> {item.num_comments} comms</a></span>|
<span className="info">{item.points} pts</span>
<span>
<Button className="btn-dismiss" onClick={() => onDismiss(item.objectID)} >
X
</Button>
</span>
</div>
<div className="col-sm-3 col-md-4"></div>
</div>
</div>
)}
</div>
)
}
function displayItem(item) {
if (typeof item.title !== "string")
return ""
else if (item.title.length > 40)
return `${item.title.substring(0, 40)}...`
else
return item.title
}
export default List
|
client/src/app.js | srtucker22/chatty | import React, { Component } from 'react';
import {
AsyncStorage,
} from 'react-native';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { ApolloProvider } from 'react-apollo';
import { composeWithDevTools } from 'redux-devtools-extension';
import { createHttpLink } from 'apollo-link-http';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { ReduxCache, apolloReducer } from 'apollo-cache-redux';
import ReduxLink from 'apollo-link-redux';
import { onError } from 'apollo-link-error';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import { PersistGate } from 'redux-persist/lib/integration/react';
import { persistStore, persistCombineReducers } from 'redux-persist';
import thunk from 'redux-thunk';
import { setContext } from 'apollo-link-context';
import _ from 'lodash';
import AppWithNavigationState, {
navigationReducer,
navigationMiddleware,
} from './navigation';
import auth from './reducers/auth.reducer';
import { logout } from './actions/auth.actions';
const URL = 'localhost:8080'; // set your comp's url here
const config = {
key: 'root',
storage: AsyncStorage,
blacklist: ['nav', 'apollo'], // don't persist nav for now
};
const reducer = persistCombineReducers(config, {
apollo: apolloReducer,
nav: navigationReducer,
auth,
});
const store = createStore(
reducer,
{}, // initial state
composeWithDevTools(
applyMiddleware(thunk, navigationMiddleware),
),
);
// persistent storage
const persistor = persistStore(store);
const cache = new ReduxCache({ store });
const reduxLink = new ReduxLink(store);
const httpLink = createHttpLink({ uri: `http://${URL}` });
// middleware for requests
const middlewareLink = setContext((req, previousContext) => {
// get the authentication token from local storage if it exists
const { jwt } = store.getState().auth;
if (jwt) {
return {
headers: {
authorization: `Bearer ${jwt}`,
},
};
}
return previousContext;
});
// afterware for responses
const errorLink = onError(({ graphQLErrors, networkError }) => {
let shouldLogout = false;
if (graphQLErrors) {
console.log({ graphQLErrors });
graphQLErrors.forEach(({ message, locations, path }) => {
console.log({ message, locations, path });
if (message === 'Unauthorized') {
shouldLogout = true;
}
});
if (shouldLogout) {
store.dispatch(logout());
}
}
if (networkError) {
console.log('[Network error]:');
console.log({ networkError });
if (networkError.statusCode === 401) {
logout();
}
}
});
// Create WebSocket client
export const wsClient = new SubscriptionClient(`ws://${URL}/graphql`, {
lazy: true,
reconnect: true,
connectionParams() {
// get the authentication token from local storage if it exists
return { jwt: store.getState().auth.jwt };
},
});
const webSocketLink = new WebSocketLink(wsClient);
const requestLink = ({ queryOrMutationLink, subscriptionLink }) =>
ApolloLink.split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
subscriptionLink,
queryOrMutationLink,
);
const link = ApolloLink.from([
reduxLink,
errorLink,
requestLink({
queryOrMutationLink: middlewareLink.concat(httpLink),
subscriptionLink: webSocketLink,
}),
]);
export const client = new ApolloClient({
link,
cache,
});
export default class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Provider store={store}>
<PersistGate persistor={persistor}>
<AppWithNavigationState />
</PersistGate>
</Provider>
</ApolloProvider>
);
}
}
|
node_modules/react-icons/md/hd.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const MdHd = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m24.1 22.5v-5h3.4v5h-3.4z m-2.5-7.5v10h6.8c0.9 0 1.6-0.7 1.6-1.6v-6.8c0-0.9-0.7-1.6-1.6-1.6h-6.8z m-3.2 10v-10h-2.5v4.1h-3.4v-4.1h-2.5v10h2.5v-3.4h3.4v3.4h2.5z m13.2-20c1.8 0 3.4 1.6 3.4 3.4v23.2c0 1.8-1.6 3.4-3.4 3.4h-23.2c-1.9 0-3.4-1.6-3.4-3.4v-23.2c0-1.8 1.5-3.4 3.4-3.4h23.2z"/></g>
</Icon>
)
export default MdHd
|
lib/components/Controls/Controls.js | christielynam/do-you | import React from 'react';
import { Link } from 'react-router-dom';
import fetchContainer from '../../containers/fetch-container';
import './Controls.css';
const handleSignOut = (props) => {
localStorage.removeItem('user');
props.removeTestsFromStore();
props.removeTestResultsFromStore();
props.removeUserFromStore();
}
const Controls = (props) => {
const { user } = props
const userName = user ? `${user.name.toUpperCase()}` : 'user'
return(
<div className='outer-container'>
<div className='controls-container'>
<div className='welcome-container'>
<h2 className='welcome-msg'>Welcome, {userName}!</h2>
<Link className='sign-out-link' to='/'><button className='sign-out-btn' onClick={() => handleSignOut(props)}>
Sign Out
</button>
</Link>
</div>
<div className='controls-links'>
<Link to='/profile'
className='profile-page'>
my profile.
</Link>
<Link to='/personality-types'
className='personality-types-page'>
personalities.
</Link>
<Link to='/assessments'
className='assessments-page'>
assessments.
</Link>
</div>
</div>
</div>
);
};
export default fetchContainer(Controls);
|
src/icons/StayCurrentPortraitIcon.js | kiloe/ui | import React from 'react';
import Icon from '../Icon';
export default class StayCurrentPortraitIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M34 2.02L14 2c-2.21 0-3.98 1.79-3.98 4v36c0 2.21 1.77 4 3.98 4h20c2.21 0 4-1.79 4-4V6c0-2.21-1.79-3.98-4-3.98zM34 38H14V10h20v28z"/></svg>;}
}; |
src/components/need/BookingAgent/Newborn.js | lethecoa/work-order-pc | import React from 'react';
import {Form, DatePicker, Input, Radio} from 'antd';
import moment from 'moment';
import {config, fun} from '../../../common';
import styles from './Newborn.less';
const RadioGroup = Radio.Group;
const RangePicker = DatePicker.RangePicker;
function Newborn( props ) {
const FormItem = Form.Item;
const { getFieldDecorator } = props.form;
return (
<div className={styles.need}>
<div className={styles.title}>需求说明</div>
<div className={styles.form}>
<FormItem {...config.formItemLayout} label="访视检查内容">
{getFieldDecorator( 'examineContent', {
initialValue: props.examineContent,
rules: [
{
required: true,
message: '请输入访视检查内容!'
},
],
} )( <Input type="textarea" rows={4} placeholder="请在此输入访视检查内容" disabled={props.disabled}/> )}
</FormItem>
<FormItem label="上午访视时间" {...config.formItemLayout}
help="时间需精确到小时(日期选择里可以切换时间显示,默认使用当前的时间)">
{getFieldDecorator( 'allowDate_am', {
initialValue: props.amInterviewTimeStart ? [
moment( new Date( parseInt( props.amInterviewTimeStart ) ), 'YYYY-MM-DD HH:mm' ),
moment( new Date( parseInt( props.amInterviewTimeEnd ) ), 'YYYY-MM-DD HH:mm' ) ] : [],
rules: [
{
required: true,
type: 'array',
message: '请选择一个时间段,精确到小时!'
},
],
} )( <RangePicker
size="small"
showTime
format="YYYY-MM-DD HH:mm"
disabled={props.disabled}
disabledDate={( current ) => current && current.valueOf() < Date.now()}
/> )}
</FormItem>
<FormItem label="下午访视时间" {...config.formItemLayout}
help="时间需精确到小时(日期选择里可以切换时间显示,默认使用当前的时间)">
{getFieldDecorator( 'allowDate_pm', {
initialValue: props.pmInterviewTimeStart ? [
moment( new Date( parseInt( props.pmInterviewTimeStart ) ), 'YYYY-MM-DD HH:mm' ),
moment( new Date( parseInt( props.pmInterviewTimeEnd ) ), 'YYYY-MM-DD HH:mm' ) ] : [],
rules: [
{
required: true,
type: 'array',
message: '请选择一个时间段,精确到小时!'
},
],
} )( <RangePicker
size="small"
showTime
format="YYYY-MM-DD HH:mm"
disabled={props.disabled}
disabledDate={( current ) => current && current.valueOf() < Date.now()}
/> )}
</FormItem>
<FormItem {...config.formItemLayout} label="是否收费">
{getFieldDecorator( 'isCharge', {
initialValue: props.isCharge ? parseInt( props.isCharge ) : 0
} )(
<RadioGroup disabled={props.disabled}>
<Radio value={1}>是</Radio>
<Radio value={0}>否</Radio>
</RadioGroup>
)}
</FormItem>
<FormItem label="预约人数" {...config.formItemLayout}>
{getFieldDecorator( 'appointmentNumberIllustration', {
initialValue: props.appointmentNumberIllustration,
rules: [
{
required: true,
message: '必须填写预约人数!'
},
],
} )( <Input placeholder="如:上午可预约3人,下午可预约5人" disabled={props.disabled}/> )}
</FormItem>
</div>
</div>
);
}
export default Form.create()( Newborn ); |
js/components/tab/configTab.js | YeisonGomez/RNAmanda |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Button, Icon, Tabs, Tab, Text, Right, Left, Body, TabHeading } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { actions } from 'react-native-navigation-redux-helpers';
import myTheme from '../../themes/base-theme';
import TabOne from './tabOne';
import TabTwo from './tabTwo';
import TabThree from './tabThree';
const {
popRoute,
} = actions;
class ConfigTab extends Component { // eslint-disable-line
static propTypes = {
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container>
<Header hasTabs>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title> Advanced Tabs</Title>
</Body>
<Right />
</Header>
<Tabs style={{ elevation: 3 }}>
<Tab heading={<TabHeading><Icon name="camera" /><Text>Camera</Text></TabHeading>}>
<TabOne />
</Tab>
<Tab heading={<TabHeading><Text>No Icon</Text></TabHeading>}>
<TabTwo />
</Tab>
<Tab heading={<TabHeading><Icon name="apps" /></TabHeading>}>
<TabThree />
</Tab>
</Tabs>
</Container>
);
}
}
function bindAction(dispatch) {
return {
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(ConfigTab);
|
packages/material-ui-icons/src/BorderTop.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7 21h2v-2H7v2zm0-8h2v-2H7v2zm4 0h2v-2h-2v2zm0 8h2v-2h-2v2zm-8-4h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2v-2H3v2zm0-4h2V7H3v2zm8 8h2v-2h-2v2zm8-8h2V7h-2v2zm0 4h2v-2h-2v2zM3 3v2h18V3H3zm16 14h2v-2h-2v2zm-4 4h2v-2h-2v2zM11 9h2V7h-2v2zm8 12h2v-2h-2v2zm-4-8h2v-2h-2v2z" />
, 'BorderTop');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.